<?php
/**
 * POST /api/journal/save-goal — Right Now Journal "Current Goal" feature
 * (production-polish pass). Creates a new active goal for an account,
 * retiring whatever goal was previously active. $auth/$db/$pdo are set up
 * by index.php's router, same pattern as api/journal/update-note.php.
 *
 * Ownership is enforced by ScopedDb::insert()/update() (always scoped to
 * user_id) plus an explicit trading_accounts ownership check before
 * touching anything, so an account_id that isn't this user's simply 404s.
 */
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'] ?? ''));
$targetBalance = (float)($input['target_balance'] ?? 0);
$reason = trim((string)($input['reason'] ?? ''));
if ($reason !== '') $reason = mb_substr($reason, 0, 500);

if ($accountId === '') {
    http_response_code(400);
    echo json_encode(['error' => 'account_id is required']);
    exit;
}
if ($targetBalance <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'target_balance must be greater than 0']);
    exit;
}

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

// Real "current balance right now" for this account — the same P&L Rule
// cascade used everywhere else in the app, not a client-supplied figure
// (the client only ever sends target_balance/reason). Deliberately NO
// is_validation filter — this is account-level balance math (same
// reasoning as src/PropFirmRuleEngine.php), and a goal set against an
// account's real balance must reflect every real trade on it, validation
// or not, since accounts are universal (Validation Workflow spec §7).
if ($account['account_type'] === 'prop_firm') {
    $caRow = $db->raw(
        "SELECT ca.account_size, ca.rules FROM challenge_accounts ca WHERE ca.account_id = :aid AND ca.user_id = :uid ORDER BY ca.created_at DESC LIMIT 1",
        [':aid' => $accountId, ':uid' => $userId]
    );
    $accountSize = !empty($caRow) ? (float)$caRow[0]['account_size'] : (float)$account['starting_balance'];
    $pnlRow = $db->raw(
        "SELECT COALESCE(SUM(COALESCE(challenge_pnl, broker_pnl, projected_pnl, 0)), 0) AS total_pnl
         FROM trades WHERE account_id = :aid AND user_id = :uid AND status = 'closed' AND deleted_at IS NULL
           AND (prop_firm_funded = 1)",
        [':aid' => $accountId, ':uid' => $userId]
    );
    // Funded-segment P&L only — a goal set on a funded account tracks
    // growth of that funded segment, not the whole evaluation history
    // (mirrors Right Now's own funded-card balance reconstruction, which
    // always restarts from account_size at each promotion).
    $currentBalance = $accountSize + (float)$pnlRow[0]['total_pnl'];
} else {
    $pnlRow = $db->raw(
        "SELECT COALESCE(SUM(COALESCE(broker_pnl, projected_pnl, 0)), 0) AS total_pnl
         FROM trades WHERE account_id = :aid AND user_id = :uid AND status = 'closed' AND deleted_at IS NULL",
        [':aid' => $accountId, ':uid' => $userId]
    );
    $currentBalance = (float)$account['starting_balance'] + (float)$pnlRow[0]['total_pnl']
        + (float)($account['net_deposits'] ?? 0) - (float)($account['net_withdrawals'] ?? 0);
}

try {
    $pdo->beginTransaction();

    $existing = $db->raw(
        "SELECT id, target_balance FROM account_goals WHERE account_id = :aid AND user_id = :uid AND status = 'active' ORDER BY created_at DESC LIMIT 1",
        [':aid' => $accountId, ':uid' => $userId]
    );
    if (!empty($existing)) {
        $wasAchieved = $currentBalance >= (float)$existing[0]['target_balance'];
        $stmt = $pdo->prepare(
            "UPDATE account_goals SET status = :status, achieved_at = :achieved_at, replaced_at = :replaced_at
             WHERE id = :id AND user_id = :uid"
        );
        $stmt->execute([
            ':status' => $wasAchieved ? 'achieved' : 'replaced',
            ':achieved_at' => $wasAchieved ? date('Y-m-d H:i:s') : null,
            ':replaced_at' => date('Y-m-d H:i:s'),
            ':id' => $existing[0]['id'],
            ':uid' => $userId,
        ]);
    }

    $goalId = $db->insert('account_goals', [
        'account_id' => $accountId,
        'starting_balance' => round($currentBalance, 2),
        'target_balance' => round($targetBalance, 2),
        'reason' => $reason !== '' ? $reason : null,
        'status' => 'active',
    ]);

    $pdo->commit();
} catch (\Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['error' => 'Could not save goal']);
    exit;
}

echo json_encode([
    'success' => true,
    'goal_id' => $goalId,
    'starting_balance' => round($currentBalance, 2),
    'target_balance' => round($targetBalance, 2),
]);
