<?php
declare(strict_types=1);

/* ==========================================================
   FX-HUNTER — AI GATE (FINAL • MONDAY SAFE)
   Confidence-aware • Warm-up enabled • Per-strategy
   ========================================================== */

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../config.php';
header("Content-Type: application/json");

// ---------------- DB CHECK ----------------if ($confidence < 50)
if (!isset($conn) || !($conn instanceof mysqli)) {
    echo json_encode([
        'ok' => true,
        'decision' => 'BLOCK',
        'reason_code' => 'DB_FAIL'
    ]);
    exit;
}

// ---------------- INPUT ----------------
$lic  = $_POST['license_key'] ?? '';
$sym  = strtoupper($_POST['symbol'] ?? '');
$tf = (int)($_POST['timeframe'] ?? 0);
$dir  = (int)($_POST['direction'] ?? 0);
$risk = (float)($_POST['risk'] ?? 0.0);
$str  = $_POST['strategy_id'] ?? 'DEFAULT';

if (
    $lic === '' ||
    $sym === '' ||
    $tf === '' ||
    !in_array($dir, [1, -1], true) ||
    $risk <= 0
) {
    echo json_encode([
        'ok' => true,
        'decision' => 'BLOCK',
        'reason_code' => 'INVALID_INPUT'
    ]);
    exit;
}

$side = ($dir === 1 ? 'buy' : 'sell');

// ==================================================
// LOAD CONFIDENCE (PER STRATEGY)
// ==================================================
$stmt = mysqli_prepare(
    $conn,
    "SELECT confidence, trades
     FROM fxh_ai_confidence
     WHERE license_key=? AND symbol=? AND strategy_id=? AND timeframe=?"
);

$confidence = 50.0;
$trades     = 0;

if ($stmt) {
    mysqli_stmt_bind_param($stmt, "sssi", $lic, $sym, $str, $tf);
    mysqli_stmt_execute($stmt);
    $r = mysqli_stmt_get_result($stmt);
    if ($row = mysqli_fetch_assoc($r)) {
        $confidence = (float)$row['confidence'];
        $trades     = (int)$row['trades'];
    }
}

// ==================================================
// DECISION LOGIC (MONDAY SAFE)
// ==================================================

// ---- Warm-up: always allow first 5 trades ----
$minTrades = 5;

if ($trades >= $minTrades && $confidence < 40) {
    echo json_encode([
        'ok'            => true,
        'decision'      => 'BLOCK',
        'approved_risk' => 0.0,
        'score'         => $confidence,
        'reason_code'   => 'LOW_CONFIDENCE'
    ]);
    exit;
}

// ---- Risk scaling (PERCENT SAFE, NEVER ZERO) ----

// Absolute minimum allowed risk = 20% of requested risk, but never below 0.01%
$minRiskFloor = max(0.01, $risk * 0.20);

if ($confidence < 50) {
    // Low confidence → heavily reduced but NEVER zero
    $approvedRisk = max($minRiskFloor, $risk * 0.30);
}
elseif ($confidence < 70) {
    // Medium confidence → moderate reduction
    $approvedRisk = max($minRiskFloor, $risk * 0.70);
}
elseif ($confidence > 85) {
    // High confidence → allow full risk (NO inflation)
    $approvedRisk = $risk;
}
else {
    // Neutral confidence
    $approvedRisk = $risk;
}

// ==================================================
// LOG DECISION (NON-BLOCKING)
// ==================================================
$snap = json_encode([
    'confidence' => $confidence,
    'trades'     => $trades,
    'risk_in'    => $risk,
    'risk_out'   => $approvedRisk
]);

$hash = hash('sha256', $snap);

$stmt = mysqli_prepare(
    $conn,
    "INSERT INTO fxh_ai_gate_decisions
     (license_id, symbol, strategy_id, side, timeframe,
      requested_risk, approved_risk,
      decision, score, reason_code,
      snapshot_json, snapshot_hash)
     VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
);

if ($stmt) {
    $decision = 'ALLOW';
    $reason   = 'PASS';
    $score    = (int)$confidence;

    mysqli_stmt_bind_param(
    $stmt,
    "ssssiddsisss",
    $lic, $sym, $str, $side, $tf,
    $risk, $approvedRisk,
    $decision, $score, $reason,
    $snap, $hash
);
    mysqli_stmt_execute($stmt);
}
// Final safety clamp — NEVER allow zero or negative risk
if ($approvedRisk <= 0) {
    $approvedRisk = $minRiskFloor;
}
// ---------------- RESPONSE ----------------
echo json_encode([
    'ok'            => true,
    'decision'      => 'ALLOW',
    'approved_risk' => $approvedRisk,
    'score'         => $confidence,
    'reason_code'   => 'PASS'
]);
