<?php
// /traderalign/api/accounts/eligible-for-promotion.php
//
// Returns accounts eligible for phase progression:
// lifecycle_state IN ('phase_1_complete', 'phase_2_complete', 'phase_3_complete')

header('Content-Type: application/json');

$userId = $auth->requireAuth();

// 2026-08-17 account-level workflow isolation — no live caller of this
// endpoint exists anywhere in the app (confirmed via grep; superseded by
// src/AccountPicker.php's apFetchAccounts(), already workflow-scoped), but
// fixed for completeness/defense-in-depth rather than left as a dormant
// unscoped query.
$epWorkflowState = ValidationService::getWorkflowState($userId, $db);

try {
    $accounts = $db->raw(
        "SELECT ca.account_id, ca.id as challenge_account_id, ca.lifecycle_state,
                ca.challenge_type, ca.rules, ca.attempt_number, ca.account_size, ca.prop_firm_name,
                ta.label as display_name
         FROM challenge_accounts ca
         JOIN trading_accounts ta ON ca.account_id = ta.id
         WHERE ca.user_id = :uid
           AND ca.lifecycle_state IN ('phase_1_complete', 'phase_2_complete', 'phase_3_complete')
           AND ca.deleted_at IS NULL
           AND ca.challenge_type != 'instant_funding'
           AND ta.workflow_context = :wfctx
         ORDER BY ca.prop_firm_name, ca.account_size, ca.attempt_number",
        [':uid' => $userId, ':wfctx' => $epWorkflowState]
    );

    foreach ($accounts as &$account) {
        $rules = json_decode($account['rules'] ?? '{}', true) ?: [];
        $account['rules_challenge_type'] = $rules['challenge_type'] ?? null;
        unset($account['rules']);
    }
    unset($account);

    echo json_encode([
        'accounts' => $accounts
    ]);
} catch (Exception $e) {
    error_log('accounts/eligible-for-promotion.php failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Failed to fetch eligible accounts. Please try again.']);
}