<?php
header('Content-Type: application/json; charset=utf-8');
/**
 * POST /api/decision/check
 * Runs full AI decision pipeline: Risk + Fraud + Limits + CashFlow
 * Returns: risk_level, action, limits, reasons, trace_id
 * SLA: <100ms
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
$_kctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$_user = $_kctx['user']; $_userId = (int)$_user['id'];
require_once __DIR__ . '/../../engine/RiskEngine.php';
require_once __DIR__ . '/../../engine/FraudGraph.php';
require_once __DIR__ . '/../../engine/SmartLimits.php';
require_once __DIR__ . '/../../engine/CashFlowEngine.php';

// session_start() removed — Kernel::handle manages sessions
header('Content-Type: application/json; charset=utf-8');
$t0 = round(microtime(true)*1000);

if ($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);die(json_encode(['error'=>'method_not_allowed']));}

$data    = json_decode(file_get_contents('php://input'),true) ?: [];
// user_id MUST come from session (not spoofable from POST)
$userId  = (int)($_SESSION['user_id'] ?? 0);
$amount  = (float)($data['amount'] ?? 0);
$service = trim($data['service'] ?? '');

if (!$userId||$amount<=0){http_response_code(422);die(json_encode(['error'=>'user_id and amount required']));}

$traceId = uniqid('dec_',true);

// Run all checks in parallel pattern (sequential for PHP)
$risk   = RiskEngine::assess($userId, $amount, $service);
$fraud  = FraudGraph::check($userId, $amount, ['ip'=>$_SERVER['REMOTE_ADDR']??null]);
$limits = SmartLimits::check($userId, $amount);
$flow   = CashFlowEngine::canAfford($userId, $amount);

// Combine decisions — MOST RESTRICTIVE WINS
$blocked = $risk['action']==='block' || $fraud['action']==='block' || !$limits['allowed'] || !$flow['can_afford'];

$finalAction = 'allow';
$reasons = [];

if (!$flow['can_afford'])       { $finalAction='block'; $reasons[]='insufficient_balance'; }
if (!$limits['allowed'])        { $finalAction='block'; $reasons[]=$limits['reason']??'limit_exceeded'; }
if ($fraud['action']==='block') { $finalAction='block'; $reasons[]='fraud_detected'; }
if ($risk['action']==='block')  { $finalAction='block'; $reasons[]='risk_critical'; }
elseif($risk['action']==='review'&&$finalAction!=='block'){$finalAction='review'; $reasons[]='risk_high';}

// Log to audit_logs
try {
    db()->prepare("INSERT INTO audit_logs (action,entity_type,entity_id,data,created_at)
                   VALUES ('decision.check','user',?,?,NOW())")
        ->execute([$userId, json_encode(compact('risk','fraud','limits','flow','finalAction'), JSON_UNESCAPED_UNICODE)]);
} catch(Throwable $e){}

$ms = round(microtime(true)*1000) - $t0;

http_response_code($blocked ? 403 : 200);
echo json_encode([
    'allowed'     => !$blocked,
    'action'      => $finalAction,
    'risk_level'  => $risk['risk_level'],
    'fraud_score' => $fraud['fraud_score'],
    'limits'      => $limits['limits'] ?? [],
    'balance'     => $flow['balance'] ?? 0,
    'can_afford'  => $flow['can_afford'],
    'reasons'     => $reasons,
    'trace_id'    => $traceId,
    'latency_ms'  => $ms,
], JSON_UNESCAPED_UNICODE);
