<?php
/**
 * POST /api/journal/clear-streak-review — Loss Streak card's "I completed
 * my review" action, the one piece of Card 2's state that can't be
 * derived purely from trade history + the clock (see
 * src/RiskPanelEngine.php's own doc comment). $auth/$db/$pdo are set up
 * by index.php's router, same pattern as api/journal/save-goal.php.
 *
 * Server-side re-verifies the account is genuinely in FULL STOP right now
 * (streak >= 8, not already covered by a newer clearance) before writing
 * anything — a client-side-only gate on this button would let a crafted
 * request record a clearance for an account that was never actually
 * stopped.
 */
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$userId = $auth->requireAuth();

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$accountId = trim((string)($input['account_id'] ?? ''));
$notes = trim((string)($input['notes'] ?? ''));
if ($notes !== '') $notes = mb_substr($notes, 0, 500);

if ($accountId === '') {
    http_response_code(400);
    echo json_encode(['error' => 'account_id is required']);
    exit;
}

$account = $db->selectById('trading_accounts', $accountId);
if (!$account) {
    http_response_code(404);
    echo json_encode(['error' => 'Account not found']);
    exit;
}

$rows = RiskPanelEngine::fetchScopedRowsForReview($accountId, $userId, $db);
$latestReview = RiskPanelEngine::latestReview($accountId, $db);
$card = RiskPanelEngine::lossStreakCard($rows, $latestReview);

if (empty($card['manual_review_owed'])) {
    http_response_code(409);
    echo json_encode(['error' => 'This account is not currently in a full-stop state — nothing to clear.']);
    exit;
}

$id = $db->insert('risk_streak_reviews', [
    'account_id' => $accountId,
    'workflow_context' => $account['workflow_context'] ?? 'main',
    'streak_at_review' => (int)$card['streak'],
    'notes' => $notes !== '' ? $notes : null,
    'cleared_at' => date('Y-m-d H:i:s'),
]);

echo json_encode(['success' => true, 'id' => $id]);
