<?php
/**
 * Account Summary View — the ONE canonical rendering of "what does this
 * account's details look like," shared by Trading Center's Account Home
 * page (public/trading-center.php) and Journal's "View Account Summary"
 * modal (public/journal.php). Built 2026-08-18, replacing two
 * independently-maintained, drifted implementations — reported directly
 * by Kevin: Trading Center's version (System Information with phase-aware
 * balance, Risk Boundary, Total Trades, Account Status, promotion state)
 * and Journal's own separate version (Identity/Strategy/Trading
 * Rules/Timeline grouping, missing Risk Boundary/Total Trades entirely)
 * showed genuinely different information for the same account, with no
 * shared source — exactly the kind of drift this app's own Single Source
 * of Truth principle exists to prevent (see CLAUDE.md's "Single Source of
 * Truth Rule (Core Account Metrics)").
 *
 * renderAccountSummarySections() renders header + breach notice (prop) +
 * System Information + Risk Boundary (prop) + Challenge Rules (prop) +
 * Ready to Promote (prop, if eligible) + Additional Details — everything
 * Trading Center's Account Home page showed ABOVE its own page-level CTA
 * buttons, since that page's presentation (the fuller of the two) is the
 * one being kept, per Kevin's own explicit direction. The caller supplies
 * the surrounding chrome — Trading Center wraps it in a back-link + its
 * own CTA row below; Journal wraps it in a modal backdrop/header/close
 * button — this function owns only the account-facts CONTENT, never
 * page-specific navigation, so the two pages can never show different
 * facts for the same account again.
 *
 * One field genuinely NEW here, present in neither original as a shared
 * concept: "Strategy Assigned" (which strategy this account's trades are
 * actually attached to) existed only in Journal's old version — kept and
 * added to System Information for both prop and live, since it's real,
 * useful account-detail info, not a performance metric, and there's no
 * reason Trading Center's Account Home shouldn't show it too.
 *
 * Depends on: src/AccountPicker.php (apAccountTradeCount, apLatestLifecycleEvent,
 * apAccountLifecycleBadge, apHumanizeLifecycleState, apLifecycleGlowBadge,
 * apChallengeRulesSummary, apPromotionPreview, apChallengeTypeLabel,
 * apExecutionModelLabel), src/PropFirmRuleEngine.php (compute()),
 * src/RenderHelpers.php (validationScopeSql) — all already globally/per-
 * page required by both callers, so this file adds no new dependency
 * either page didn't already have.
 */

/** Broker name parsed from a live account's own "{Broker} - {Nickname}" label convention (api/accounts/create.php). Deliberately separate from trading-center.php's own tcParseBroker() — that one also drives broker-GROUPING/routing logic elsewhere on that page and must stay untouched; this is only ever used for the summary's own display row. */
function asvBrokerFromLabel(string $label): string {
    return trim(explode(' - ', $label, 2)[0]);
}

function renderAccountSummarySections(array $account, string $kind, ScopedDb $db, PDO $pdo, string $userId, string $workflowState = 'main'): void {
    $lifecycleState = $account['lifecycle_state'] ?? '';
    $tradeCount = apAccountTradeCount($account['id'], $db, $workflowState);

    // Strategy Assigned — see this file's header comment. Scoped to the
    // CURRENT workflow's own trades (same validationScopeSql() reasoning
    // already established elsewhere for this exact query shape), never a
    // stale cross-workflow read on a shared account.
    $strategyName = null;
    try {
        $stratCond = validationScopeSql($workflowState, 't');
        $svRow = $db->raw(
            "SELECT s.name FROM trades t
             JOIN strategy_versions sv ON sv.id = t.strategy_version_id
             JOIN strategies s ON s.id = sv.strategy_id
             WHERE t.account_id = :aid AND t.user_id = :uid AND t.strategy_version_id IS NOT NULL AND {$stratCond}
             ORDER BY t.captured_at DESC LIMIT 1",
            [':aid' => $account['id'], ':uid' => $userId]
        );
        if (!empty($svRow)) $strategyName = trim($svRow[0]['name']);
    } catch (\Throwable $e) { $strategyName = null; }
    $strategyDisplay = $strategyName ? htmlspecialchars($strategyName) : 'No strategy attached to this account\'s trades yet';

    if ($kind === 'prop') {
        $rules = json_decode($account['rules'] ?? '{}', true) ?: [];
        $challengeType = $account['challenge_type'] ?? '';
        $promoEvent = apLatestLifecycleEvent($account['id'], ['PHASE_2_STARTED', 'PHASE_3_STARTED', 'FUNDED_ACTIVATED'], $pdo);
        [$statusLabel] = apAccountLifecycleBadge($lifecycleState);
        $rulesSummary = apChallengeRulesSummary($rules, $challengeType, $lifecycleState);
        $isBreached = $lifecycleState === 'breached';
        $isPromotable = str_contains($lifecycleState, '_complete');
        $promoPreview = $isPromotable ? apPromotionPreview($lifecycleState, $challengeType) : null;

        // Phase-aware current balance (2026-08-08) — see
        // docs/architecture/SINGLE_SOURCE_OF_TRUTH_AUDIT.md §1g. Falls back
        // to the raw whole-ledger field only if PropFirmRuleEngine can't
        // resolve this account (shouldn't happen for a real prop account,
        // but fails safe rather than blank).
        $pfrDisplay = PropFirmRuleEngine::compute($account['id']);
        $displayBalance = !isset($pfrDisplay['error']) ? (float)$pfrDisplay['phase_balance'] : (float)$account['current_balance'];
        ?>
        <div class="tc-summary-head">
            <div>
                <div class="tc-summary-title"><?= htmlspecialchars($account['label']) ?></div>
                <div class="tc-summary-sub"><?= htmlspecialchars($account['prop_firm_name'] ?? '') ?> · <?= htmlspecialchars(apChallengeTypeLabel($challengeType)) ?></div>
            </div>
            <?= apLifecycleGlowBadge($lifecycleState) ?>
        </div>

        <?php if ($isBreached): ?>
        <!-- Professional, factual, non-encouraging — states the fact, states
             the one real consequence, and stops there. -->
        <div class="tc-breach-notice">
            <span class="tc-breach-icon">⚠</span>
            <div>
                <div class="tc-breach-title">This account has been breached</div>
                <div class="tc-breach-sub">Its evaluation has ended. Any trades placed here going forward will not count toward a prop firm challenge.</div>
            </div>
        </div>
        <?php endif; ?>

        <div class="tc-summary-section">
            <h3>System Information</h3>
            <div class="tc-summary-grid">
                <div class="tc-row"><span>Date Added</span><span><?= htmlspecialchars(date('M j, Y', strtotime($account['created_at']))) ?></span></div>
                <div class="tc-row"><span>Attempt Number</span><span><?= (int)($account['attempt_number'] ?? 1) ?></span></div>
                <div class="tc-row"><span>Current Stage</span><span><?= htmlspecialchars(apHumanizeLifecycleState($lifecycleState)) ?></span></div>
                <div class="tc-row"><span>Total Trades</span><span><?= $tradeCount ?></span></div>
                <div class="tc-row"><span>Current Balance</span><span>$<?= number_format($displayBalance, 2) ?></span></div>
                <div class="tc-row"><span>Account Status</span><span><?= htmlspecialchars($statusLabel) ?></span></div>
                <div class="tc-row"><span>Strategy Assigned</span><span><?= $strategyDisplay ?></span></div>
                <div class="tc-row"><span>Promotion Date</span><span><?= $promoEvent ? htmlspecialchars(date('M j, Y', strtotime($promoEvent['occurred_at']))) : '-' ?></span></div>
                <?php if ($isBreached): ?>
                <div class="tc-row"><span>Breach Date</span><span><?= !empty($account['breached_at']) ? htmlspecialchars(date('M j, Y', strtotime($account['breached_at']))) : '-' ?></span></div>
                <div class="tc-row"><span>Breach Reason</span><span><?= htmlspecialchars($account['current_outcome'] ?: 'Not recorded') ?></span></div>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!isset($pfrDisplay['error']) && !$isBreached): ?>
        <!-- Current breach boundary / remaining risk capacity — the one
             standardized risk-status output every Maximum Loss Model
             (Fixed/Trailing) resolves down to via PropFirmRuleEngine::compute();
             the model only changes which dollar figures these rows show,
             never their meaning. -->
        <div class="tc-summary-section">
            <h3>Risk Boundary</h3>
            <div class="tc-summary-grid">
                <div class="tc-row"><span>Breach Level</span><span>$<?= number_format((float)$pfrDisplay['overall_drawdown']['breach_level_amount'], 2) ?></span></div>
                <div class="tc-row"><span>Remaining Room</span><span>$<?= number_format((float)$pfrDisplay['overall_drawdown']['remaining_amount'], 2) ?></span></div>
                <?php if (($pfrDisplay['overall_drawdown']['max_loss_model'] ?? 'fixed') === 'trailing'): ?>
                <div class="tc-row"><span>Current Peak</span><span>$<?= number_format((float)$pfrDisplay['overall_drawdown']['peak_balance'], 2) ?></span></div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="tc-summary-section">
            <h3>Challenge Rules</h3>
            <div class="tc-summary-grid">
                <?php foreach ($rulesSummary as $label => $value): ?>
                <div class="tc-row"><span><?= htmlspecialchars($label) ?></span><span><?= htmlspecialchars($value) ?></span></div>
                <?php endforeach; ?>
                <div class="tc-row"><span>Account Size</span><span>$<?= number_format((float)($account['account_size'] ?? 0), 2) ?></span></div>
                <div class="tc-row"><span>Leverage</span><span><?= htmlspecialchars($account['leverage'] ?: 'Not specified') ?></span></div>
            </div>
        </div>

        <?php if ($isPromotable && $promoPreview): ?>
        <div class="tc-summary-section">
            <div class="tc-summary-section-head"><h3>Ready to Promote</h3></div>
            <div class="tc-promo-row"><span>Current State</span><span><?= htmlspecialchars($promoPreview['from']) ?></span></div>
            <div class="tc-promo-arrow">↓</div>
            <div class="tc-promo-row"><span>Will Promote To</span><span><?= htmlspecialchars($promoPreview['to']) ?></span></div>
            <div id="tc-promo-error" class="tc-promo-error"></div>
            <div style="margin-top:.85rem">
                <button type="button" class="btn btn-primary btn-md" id="tc-promote-btn"
                        onclick="tcPromoteAccount('<?= htmlspecialchars($account['id']) ?>', '<?= htmlspecialchars($lifecycleState) ?>', '<?= htmlspecialchars($challengeType) ?>')">Promote Account →</button>
            </div>
            <div class="tc-hint" style="margin-top:.75rem">This phase is already complete. Promoting moves the account to its next stage.</div>
        </div>
        <?php endif; ?>

        <?php renderAccountAdditionalDetails($account, 'prop'); ?>
        <?php
    } else {
        // Live/personal account.
        $broker = asvBrokerFromLabel($account['label']);
        ?>
        <div class="tc-summary-head">
            <div>
                <div class="tc-summary-title"><?= htmlspecialchars($account['label']) ?></div>
                <div class="tc-summary-sub">Live Account · <?= htmlspecialchars(apExecutionModelLabel($account['execution_model'] ?? null)) ?></div>
            </div>
            <?= apLifecycleGlowBadge($lifecycleState) ?>
        </div>

        <div class="tc-summary-section">
            <h3>System Information</h3>
            <div class="tc-summary-grid">
                <div class="tc-row"><span>Date Added</span><span><?= htmlspecialchars(date('M j, Y', strtotime($account['created_at']))) ?></span></div>
                <div class="tc-row"><span>Broker</span><span><?= htmlspecialchars($broker) ?></span></div>
                <div class="tc-row"><span>Current Balance</span><span>$<?= number_format((float)$account['current_balance'], 2) ?></span></div>
                <div class="tc-row"><span>Starting Balance</span><span>$<?= number_format((float)($account['starting_balance'] ?? 0), 2) ?></span></div>
                <div class="tc-row"><span>Total Trades</span><span><?= $tradeCount ?></span></div>
                <div class="tc-row"><span>Currency</span><span><?= htmlspecialchars($account['currency'] ?? 'USD') ?></span></div>
                <div class="tc-row"><span>Strategy Assigned</span><span><?= $strategyDisplay ?></span></div>
            </div>
        </div>

        <?php renderAccountAdditionalDetails($account, 'live'); ?>
        <?php
    }
}

/**
 * Additional Details — Platform/Server/Login/Password/Account Number/
 * (Execution Model, live only)/Tags/Notes, plus the shared "Edit Account
 * Details" modal. Moved verbatim from trading-center.php's own
 * tcRenderAdditionalDetails() (byte-identical markup/classes/element ids)
 * — the modal's JS (tcOpenMetaModal/tcCloseMetaModal/tcSaveMeta/
 * tcRevealSecret, assets/js/account-summary.js) and CSS
 * (assets/css/account-summary.css) are now loaded by both pages, so this
 * one rendering + its one edit flow is genuinely shared, not just
 * visually similar.
 */
function renderAccountAdditionalDetails(array $account, string $kind): void {
    $fields = [
        'Platform' => $account['platform'] ?: 'Not set',
        'Server' => $account['broker_server'] ?: 'Not set',
        'Login' => $account['broker_login'] ?: 'Not set',
        'Account Number' => $account['account_number'] ?: 'Not set',
    ];
    if ($kind === 'live') {
        $fields['Execution Model'] = apExecutionModelLabel($account['execution_model'] ?? null);
    }
    $tags = !empty($account['tags']) ? (json_decode($account['tags'], true) ?: []) : [];
    $fields['Tags'] = $tags ? implode(', ', $tags) : 'None';
    $fields['Notes'] = $account['account_notes'] ?: 'None';
    $hasPassword = !empty($account['broker_password_encrypted']);
    ?>
    <div class="tc-summary-section">
        <div class="tc-summary-section-head">
            <h3>Additional Details</h3>
            <button type="button" class="tc-edit-btn" onclick="tcOpenMetaModal()">✎ Edit</button>
        </div>
        <div class="tc-summary-grid">
            <?php foreach ($fields as $label => $value): ?>
            <div class="tc-row"><span><?= htmlspecialchars($label) ?></span><span><?= htmlspecialchars($value) ?></span></div>
            <?php endforeach; ?>
            <div class="tc-row">
                <span>Password</span>
                <span>
                    <?php if ($hasPassword): ?>
                    <span id="tc-pw-display">••••••••</span>
                    <button type="button" class="tc-reveal-btn" onclick="tcRevealSecret(this, <?= json_encode($account['id']) ?>)" data-revealed="0">👁</button>
                    <?php else: ?>Not set<?php endif; ?>
                </span>
            </div>
        </div>
    </div>

    <div class="tc-modal-backdrop" id="tc-meta-backdrop" style="display:none" onclick="if(event.target===this) tcCloseMetaModal()">
        <div class="tc-modal-panel">
            <div class="tc-modal-head">
                <h3>Edit Additional Details</h3>
                <button type="button" class="tc-modal-close" onclick="tcCloseMetaModal()">✕</button>
            </div>
            <div class="tc-modal-body">
                <label>Platform
                    <select id="tc-meta-platform">
                        <option value="">- Not set -</option>
                        <?php foreach (['MT4', 'MT5', 'cTrader', 'DXtrade', 'Match-Trader', 'TradeLocker', 'Other'] as $p): ?>
                        <option value="<?= $p ?>" <?= ($account['platform'] ?? '') === $p ? 'selected' : '' ?>><?= $p ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>Server <input type="text" id="tc-meta-server" value="<?= htmlspecialchars($account['broker_server'] ?? '') ?>"></label>
                <label>Login <input type="text" id="tc-meta-login" value="<?= htmlspecialchars($account['broker_login'] ?? '') ?>"></label>
                <label>Account Number <input type="text" id="tc-meta-account-number" value="<?= htmlspecialchars($account['account_number'] ?? '') ?>"></label>
                <?php if ($kind === 'live'): ?>
                <label>Execution Model
                    <select id="tc-meta-execution-model">
                        <option value="">- Not Categorized -</option>
                        <?php foreach (apExecutionModelCategories() as $key => $cat): ?>
                        <option value="<?= $key ?>" title="<?= htmlspecialchars($cat['tooltip']) ?>" <?= ($account['execution_model'] ?? '') === $key ? 'selected' : '' ?>><?= htmlspecialchars($cat['label']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <?php endif; ?>
                <label>Password <input type="password" id="tc-meta-password" placeholder="<?= $hasPassword ? 'Leave blank to keep current' : '' ?>"></label>
                <?php if ($hasPassword): ?>
                <label class="tc-checkbox-label"><input type="checkbox" id="tc-meta-password-clear"> Clear stored password</label>
                <?php endif; ?>
                <label>Tags (comma-separated) <input type="text" id="tc-meta-tags" value="<?= htmlspecialchars(implode(', ', $tags)) ?>"></label>
                <label>Notes <textarea id="tc-meta-notes" rows="3"><?= htmlspecialchars($account['account_notes'] ?? '') ?></textarea></label>
                <div id="tc-meta-error" class="tc-modal-error" style="display:none"></div>
            </div>
            <div class="tc-modal-foot">
                <button type="button" class="btn btn-outline btn-md" onclick="tcCloseMetaModal()">Cancel</button>
                <button type="button" class="btn btn-primary btn-md" id="tc-meta-save-btn" onclick="tcSaveMeta('<?= htmlspecialchars($account['id']) ?>')">Save</button>
            </div>
        </div>
    </div>
    <?php
}
