<?php
/**
 * POST /api/journal/reveal-account-secret — Right Now Journal Account
 * Summary item 9: the ONE endpoint that ever decrypts and returns the
 * stored broker password. Deliberately separate from
 * update-account-meta.php's read/write path so a page render (or that
 * endpoint's own JSON response) can never leak the plaintext value by
 * accident — this only fires on an explicit, user-initiated "👁 Reveal"
 * click.
 */
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;
}

// selectById() is scoped to this user's own trading_accounts rows — a
// foreign account_id simply 404s, never decrypts another user's secret.
$account = $db->selectById('trading_accounts', $accountId);
if (!$account) {
    http_response_code(404);
    echo json_encode(['error' => 'Account not found']);
    exit;
}

$plain = CredentialCrypto::decrypt($account['broker_password_encrypted'] ?? null);
echo json_encode(['success' => true, 'password' => $plain]);
