<?php
declare(strict_types=1);

require_once "/var/www/html/portal/config.php";

if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    echo "DB_CONN_FAIL";
    exit;
}

$db = $conn;
if(!$db){ echo "DB_FAIL"; exit; }

$data = [];
parse_str(file_get_contents("php://input"), $data);

$lic   = $data['license_key'] ?? '';
$sym   = strtoupper($data['symbol'] ?? '');
$tf    = intval($data['timeframe'] ?? 0);
$strat = $data['strategy_id'] ?? 'DEFAULT';

$net   = floatval($data['net_profit'] ?? 0);
$conf0 = floatval($data['confidence_start'] ?? 50);
$conf1 = floatval($data['confidence_end'] ?? $conf0);
$disc  = intval($data['discipline_ok'] ?? 0); // 1 = SL/RunUp respected

if($lic==='' || $sym==='' || $tf<=0){
    echo "INVALID_INPUT";
    exit;
}

/* ==========================================================
   AI CONFIDENCE UPDATE — SAFE / EXPLICIT / FINAL
   ========================================================== */

// ---------------- calculate deltas ----------------
$delta = 0.0;
$winInc = 0;

if ($net > 0.01) {
    $delta  = 2.0;
    $winInc = 1;
}
elseif ($net < -0.01) {
    $delta  = -3.5;
}
else {
    $delta  = -0.5;
}

// management quality
$delta += ($conf1 - $conf0) * 0.6;

// ---------------- check existing row ----------------
$stmt = $db->prepare("
SELECT id, confidence, trades, wins, expectancy
FROM fxh_ai_confidence
WHERE license_key=? AND symbol=? AND strategy_id=? AND timeframe=?
");

$stmt->bind_param("sssi", $lic, $sym, $strat, $tf);
$stmt->execute();
$res = $stmt->get_result();

if ($row = $res->fetch_assoc()) {

    // ===== UPDATE PATH =====
    $id         = (int)$row['id'];
    $confidence = max(0, min(100, $row['confidence'] + $delta));
    $trades     = $row['trades'] + 1;
    $wins       = $row['wins'] + $winInc;
    $expectancy = (($row['expectancy'] * $row['trades']) + $net) / $trades;

    $stmt = $db->prepare("
        UPDATE fxh_ai_confidence
        SET confidence=?, trades=?, wins=?, expectancy=?, updated_at=NOW()
        WHERE id=?
    ");

    $stmt->bind_param(
        "diidi",
        $confidence,
        $trades,
        $wins,
        $expectancy,
        $id
    );

    $stmt->execute();

} else {

    // ===== INSERT PATH =====
    $confidence = max(0, min(100, 50 + $delta));
    $trades     = 1;
    $wins       = $winInc;
    $expectancy = $net;

    $stmt = $db->prepare("
        INSERT INTO fxh_ai_confidence
        (license_key, symbol, strategy_id, timeframe,
         confidence, trades, wins, expectancy, updated_at)
        VALUES (?,?,?,?,?,?,?,?,NOW())
    ");

    $stmt->bind_param(
        "sssiddid",
        $lic,
        $sym,
        $strat,
        $tf,
        $confidence,
        $trades,
        $wins,
        $expectancy
    );

    $stmt->execute();
}

echo "OK";
