<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/SuggestionsAgent.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }

$b  = json_decode(file_get_contents('php://input'), true) ?? [];
$id = (int)($b['id'] ?? 0);
if (!$id) { http_response_code(400); die(json_encode(['error'=>'id_required'])); }

try {
    $st = db()->prepare("SELECT * FROM user_suggestions WHERE id=? LIMIT 1");
    $st->execute([$id]);
    $sug = $st->fetch();
    if (!$sug) { http_response_code(404); die(json_encode(['error'=>'not_found'])); }

    $analysis = SuggestionsAgent::analyze([
        'type'             => $sug['type'],
        'service'          => $sug['service'],
        'description'      => $sug['description'],
        'expected_benefit' => $sug['expected_benefit'],
        'user_plan'        => $sug['user_plan'] ?? 'free',
    ]);

    db()->prepare(
        "UPDATE user_suggestions SET priority_score=?,priority_label=?,ai_summary=?,
         ai_recommendation=?,affected_estimate=?,effort_level=?,team_responsible=?
         WHERE id=?"
    )->execute([
        $analysis['priority_score'],$analysis['priority_label'],
        $analysis['ai_summary'],$analysis['ai_recommendation'],
        $analysis['affected_estimate'],$analysis['effort_level'],
        $analysis['team_responsible'],$id,
    ]);

    echo json_encode(['ok'=>true,'analysis'=>$analysis], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
