<?php
$userId = $auth->requireAuth();

// Fetch prop_firm_name if account_id is provided
// 2026-08-17 account-level workflow isolation: selectById() only scopes by
// user_id (it's a generic helper, used for many tables where workflow
// doesn't apply) — verify this specific account actually belongs to the
// user's CURRENT workflow before trusting anything read from it, same as
// every other direct account lookup in the app now does.
$propFirmName = '';
$accountId = $_GET['account_id'] ?? null;
if ($accountId) {
    $account = $db->selectById('trading_accounts', $accountId);
    if ($account && ($account['workflow_context'] ?? 'main') !== ValidationService::getWorkflowState($userId, $db)) {
        $account = null;
    }
    if ($account && !empty($account['prop_firm_name'])) {
        $propFirmName = $account['prop_firm_name'];
    }
}

// Build query params for iframe - include all GET params plus tier and prop_firm_name
$tier = 'free';
$profile = $db->selectById('user_profiles', $userId, 'user_id');
if ($profile && !empty($profile['tier'])) {
    $tier = $profile['tier'];
}

// Merge all params: existing GET params + tier + prop_firm_name + timestamp
$iframeParams = array_merge($_GET, [
    'tier' => $tier,
    '_ts' => time()
]);

// Override/add prop_firm_name if we found it
if ($propFirmName) {
    $iframeParams['prop_firm_name'] = $propFirmName;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator - TraderAlign</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/traderalign/assets/tokens.css">
<link rel="icon" type="image/png" sizes="32x32" href="/traderalign/assets/favicon/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/traderalign/assets/favicon/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/traderalign/assets/favicon/apple-touch-icon.png">
    <link rel="shortcut icon" href="/traderalign/assets/favicon/favicon.ico">
<link rel="stylesheet" href="/traderalign/assets/css/brand.css">
<style>
*{margin:0;padding:0;box-sizing:border-box}
.dash-layout{display:flex;min-height:100vh;background:var(--background)}
.sidebar{width:4rem;background:var(--sidebar);border-right:1px solid var(--sidebar-border);display:flex;flex-direction:column;align-items:center;padding-top:1rem;gap:.25rem;position:fixed;top:0;left:0;bottom:0;z-index:40}
.sidebar a{display:flex;align-items:center;justify-content:center;width:2.75rem;height:2.75rem;border-radius:var(--radius-md);color:var(--foreground-dim);transition:background var(--t-fast),color var(--t-fast);position:relative}
.sidebar a:hover{background:var(--background-surface);color:var(--foreground)}
.sidebar a.active{background:var(--background-surface);color:var(--sidebar-primary)}
.sidebar a .tt{position:absolute;left:3.5rem;background:var(--popover);color:var(--foreground);font-size:.75rem;padding:.25rem .625rem;border-radius:var(--radius-sm);white-space:nowrap;pointer-events:none;opacity:0;transition:opacity var(--t-fast)}
.sidebar a:hover .tt{opacity:1}
.main{margin-left:4rem;flex:1;display:flex}
.main iframe{width:100%;height:100vh;border:none}
</style>
</head>
<body class="dash-layout">

<?php include __DIR__ . '/sidebar.php'; ?>

<main class="main">
    <iframe src="/traderalign/calculator-source.html?<?= http_build_query($iframeParams) ?>"></iframe>
</main>

<script>
// ── LIFECYCLE-ID HANDSHAKE FALLBACK ──────────────────────────────────────
// Answers the calculator iframe if it ever reads sessionStorage as null
// for trade_lifecycle_id (e.g. a stale/bfcache-restored iframe document).
// This page (calculator.php) and the checklist page share the same
// top-level origin, so this window's own sessionStorage is the same
// store the checklist wrote into — we just hand it back on request.
window.addEventListener('message', function(event) {
    if (event.origin !== window.location.origin) return;
    if (!event.data || event.data.type !== 'TRADERALIGN_REQUEST_LIFECYCLE_IDS') return;

    var iframe = document.querySelector('.main iframe');
    if (!iframe || event.source !== iframe.contentWindow) return;

    iframe.contentWindow.postMessage({
        type: 'TRADERALIGN_LIFECYCLE_IDS',
        payload: {
            trade_lifecycle_id: sessionStorage.getItem('trade_lifecycle_id'),
            strategy_version_id: sessionStorage.getItem('strategy_version_id'),
            account_id: sessionStorage.getItem('account_id'),
            challenge_account_id: sessionStorage.getItem('challenge_account_id'),
            current_stage: sessionStorage.getItem('current_stage'),
            account_rules: sessionStorage.getItem('account_rules'),
            prop_firm_mode: sessionStorage.getItem('prop_firm_mode')
        }
    }, window.location.origin);
});
</script>

</body>
</html>