<?php
/**
 * POST /api/journal/update-account-meta — Right Now Journal Account Summary
 * refinement (items 9/10): Platform/Server/Login/Password/Account Number/
 * Tags/Notes become real, editable, persisted account metadata (previously
 * every one of these was a hardcoded "Not tracked"/"not supported yet"
 * message). $auth/$db/$pdo are set up by index.php's router, same pattern
 * as api/journal/update-note.php / save-goal.php.
 *
 * Each field is only touched when its key is actually present in the
 * request body (array_key_exists, not just truthy) — an empty string
 * clears that field, an omitted key leaves it exactly as it was. This lets
 * the client send just the one field it edited, matching the per-field
 * ✏/➕ affordances on the Account Summary panel, without silently wiping
 * every other field on each save.
 *
 * broker_password is the one field never round-tripped back to the
 * client in cleartext from this endpoint (only encrypted at rest via
 * CredentialCrypto and only ever decrypted by the dedicated, explicit
 * reveal endpoint) — a personal reference field only, never used by
 * TraderAlign to log into a broker platform on the trader's behalf.
 */
header('Content-Type: application/json');
require_once __DIR__ . '/../../src/CredentialCrypto.php';

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'] ?? ''));
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;
}

$ALLOWED_PLATFORMS = ['MT4', 'MT5', 'cTrader', 'DXtrade', 'Match-Trader', 'TradeLocker', 'Other'];

$data = [];
if (array_key_exists('platform', $input)) {
    $platform = trim((string)$input['platform']);
    $data['platform'] = $platform === '' ? null : (in_array($platform, $ALLOWED_PLATFORMS, true) ? $platform : mb_substr($platform, 0, 50));
}
if (array_key_exists('broker_server', $input)) {
    $v = trim((string)$input['broker_server']);
    $data['broker_server'] = $v === '' ? null : mb_substr($v, 0, 100);
}
if (array_key_exists('broker_login', $input)) {
    $v = trim((string)$input['broker_login']);
    $data['broker_login'] = $v === '' ? null : mb_substr($v, 0, 100);
}
if (array_key_exists('broker_password', $input)) {
    $v = (string)$input['broker_password'];
    $data['broker_password_encrypted'] = $v === '' ? null : CredentialCrypto::encrypt(mb_substr($v, 0, 200));
}
if (array_key_exists('account_number', $input)) {
    $v = trim((string)$input['account_number']);
    $data['account_number'] = $v === '' ? null : mb_substr($v, 0, 100);
}
if (array_key_exists('tags', $input)) {
    // Accepts either a real array or a comma-separated string (the edit
    // modal posts a comma-separated string from one plain text input —
    // no new tagging UI component, same "small amount of structure" the
    // migration's own comment settled on).
    $rawTags = $input['tags'];
    $list = is_array($rawTags) ? $rawTags : explode(',', (string)$rawTags);
    $tags = [];
    foreach ($list as $tag) {
        $tag = trim((string)$tag);
        if ($tag === '') continue;
        $tag = mb_substr($tag, 0, 30);
        if (!in_array($tag, $tags, true)) $tags[] = $tag;
        if (count($tags) >= 15) break;
    }
    $data['tags'] = empty($tags) ? null : json_encode($tags);
}
if (array_key_exists('account_notes', $input)) {
    $v = trim((string)$input['account_notes']);
    $data['account_notes'] = $v === '' ? null : mb_substr($v, 0, 4000);
}
if (array_key_exists('execution_model', $input)) {
    // Trading Center redesign — Live Trading Center execution-model
    // categorization (migration_add_execution_model.sql). Personal
    // accounts only in practice, but not enforced here — same
    // allow-list-or-null pattern as `platform` above.
    $ALLOWED_EXECUTION_MODELS = ['ecn', 'stp', 'standard', 'raw_spread'];
    $execModel = trim((string)$input['execution_model']);
    $data['execution_model'] = ($execModel === '' || !in_array($execModel, $ALLOWED_EXECUTION_MODELS, true)) ? null : $execModel;
}

if (empty($data)) {
    http_response_code(400);
    echo json_encode(['error' => 'No recognized fields to update']);
    exit;
}

$db->update('trading_accounts', $accountId, $data);

$responseTags = [];
if (array_key_exists('tags', $data)) {
    $responseTags = $data['tags'] !== null ? (json_decode($data['tags'], true) ?: []) : [];
}

echo json_encode([
    'success' => true,
    'platform' => $data['platform'] ?? null,
    'broker_server' => $data['broker_server'] ?? null,
    'broker_login' => $data['broker_login'] ?? null,
    'has_password' => array_key_exists('broker_password_encrypted', $data) ? $data['broker_password_encrypted'] !== null : null,
    'account_number' => $data['account_number'] ?? null,
    'tags' => $responseTags,
    'account_notes' => $data['account_notes'] ?? null,
    'execution_model' => $data['execution_model'] ?? null,
]);
