<?php
/**
 * POST /api/journal/update-note — Right Now Journal item 11: trade notes
 * are now a real, editable, permanent field (trades.notes, added by
 * migration_add_trade_notes.sql), not a hardcoded placeholder.
 *
 * $auth/$db are already set up by index.php's router (same pattern as
 * api/journal/trades-more.php). Scoped to the current user via
 * ScopedDb::update() (WHERE user_id = :uid AND id = :id) — a trade_id that
 * doesn't belong to this user simply updates zero rows, never another
 * user's data.
 */
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;
$tradeId = trim((string)($input['trade_id'] ?? ''));
$notes = (string)($input['notes'] ?? '');

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

// Cap length defensively — this is a journal note, not a document store.
// 1800 chars ≈ 300 words (2026-08-04 Journal polish pass) — must match
// public/journal.php's RN_NOTE_MAX_LENGTH constant (that file can't be
// require'd here without executing the whole page, so this is a mirrored
// literal, same "mirror, not shared module" precedent already used for
// AnalyticsEngine::INSTRUMENT_SPECS vs. calculator-source.html).
$notes = mb_substr(trim($notes), 0, 1800);

$ok = $db->update('trades', $tradeId, ['notes' => $notes === '' ? null : $notes]);

if (!$ok) {
    // Either the trade doesn't exist, doesn't belong to this user, or the
    // note text was unchanged (rowCount() = 0 for an identical value too) —
    // re-check ownership so the caller gets an honest 404 vs. a silent 200.
    $exists = $db->selectById('trades', $tradeId);
    if (!$exists) {
        http_response_code(404);
        echo json_encode(['error' => 'Trade not found']);
        exit;
    }
}

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