<?php
// Determine which icon is active based on the current URL
$currentPage = basename($_SERVER['SCRIPT_NAME'], '.php');

function sidebarLink($page, $currentPage) {
    return '/traderalign/' . $page;
}

// Validation Workflow — the ONE real "which nav does this user see" read.
// user_profiles.workflow_state (ValidationService::getWorkflowState()) is
// the single first-class field for this, not the old journey_type-derived
// $showDevLinks (which only ever appended Learning Center/Strategy
// Validation/Validation Journal links AFTER Colex without ever removing
// Reports/Strategy — the validation workflow spec requires a full swap,
// not an append). Same defensive $GLOBALS['pdo'] pattern the old code
// used, since some callers may require this file before $auth/$db are
// guaranteed to be in scope.
$workflowState = 'main';
if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    try {
        $sidebarAuth = new Auth($GLOBALS['pdo']);
        if ($sidebarAuth->isLoggedIn()) {
            $sidebarDb = $GLOBALS['db'] ?? new ScopedDb($GLOBALS['pdo'], $sidebarAuth->getUserId());
            $sidebarUserId = $sidebarAuth->getUserId();
            $workflowState = ValidationService::getWorkflowState($sidebarUserId, $sidebarDb);
        }
    } catch (\Throwable $e) {
        // Silently fail — don't break the sidebar if the query fails. Same
        // fallback the old code used: default to 'main', the normal nav.
    }
}
$isValidatingNav = $workflowState === 'validation';

// 2026-08-19 security fix (CSRF): sidebar.php is the one file included by
// nearly every authenticated page, which makes it the natural single place
// to emit the CSRF token meta tag + the shared fetch() wrapper that reads
// it — every page's existing fetch() call sites (colex.php, journal.php,
// trading-center.php, drafts.php, calculator-source.html, strategy.php,
// etc.) automatically start carrying an X-CSRF-Token header with zero
// changes to any of those individual files. See src/Csrf.php and
// assets/js/csrf.js for the full explanation; enforcement is centralized
// in index.php. Requires src/Csrf.php — already loaded globally by
// index.php, but require_once'd here too so this file stays safe if ever
// included from a context that hasn't loaded it yet.
require_once __DIR__ . '/../src/Csrf.php';
// 2026-08-18 correction: "Back to Main Workflow" must NEVER appear in or
// around the sidebar, in any form — explicit instruction, reversing the
// immediately-prior pass's own fixed-position-button-above-the-nav
// attempt. It now lives entirely on the Dashboard, in the exact spot the
// "Open Validation Tracker →" shortcut used to occupy (public/dashboard.php,
// $dashCanReturnToMain) — the sidebar still carries a real "Validation
// Tracker" icon while validating (below), but no return-to-main control of
// any kind. This file no longer needs ValidationService::getEntrySource()
// at all (it was only ever fetched to decide that now-removed control's
// visibility), so that extra per-request query is gone too.
?>
<?= Csrf::metaTag() ?>
<script src="/traderalign/assets/js/csrf.js"></script>
<nav class="sidebar">
    <a href="<?= sidebarLink('dashboard', $currentPage) ?>" title="TraderAlign" style="margin-bottom:.5rem">
        <img src="/traderalign/images/logo.png" alt="TraderAlign" class="ta-logo ta-logo--lg">
    </a>
    <div style="width:1.75rem;height:1px;background:rgba(255,255,255,.14);margin:.1rem 0 .65rem;flex-shrink:0"></div>
    <a href="<?= sidebarLink('dashboard', $currentPage) ?>" title="Dashboard" class="<?= $currentPage === 'dashboard' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
    </a>
    <a href="/traderalign/trading-center" title="Trading Center" class="<?= $currentPage === 'trading-center' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
    </a>
    <?php if ($isValidatingNav): ?>
    <a href="/traderalign/strategy-validation" title="Validation Strategy" class="<?= $currentPage === 'strategy-validation' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18"/></svg>
    </a>
    <?php endif; ?>
    <a href="<?= sidebarLink('drafts', $currentPage) ?>" title="Drafts" class="<?= $currentPage === 'drafts' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
    </a>
    <!-- 2026-08-18 correction: Journal is real, shared infrastructure for
         BOTH workflows, always shown here, journal.php no longer gates a
         validating user away (it renders Active Journeys scoped to that
         workflow's own accounts/trades via trading_accounts.workflow_context
         and validationScopeSql(), the same isolation Trading Center's own
         account picker already enforces). "Validation Tracker" below is a
         separate, additional progress-tracking page, not a substitute for
         this link. -->
    <a href="/traderalign/journal" title="Journal" class="<?= $currentPage === 'journal' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20V2H6.5A2.5 2.5 0 0 0 4 4.5v15z"/><path d="M8 7h8M8 11h8"/></svg>
    </a>
    <?php if ($isValidatingNav): ?>
    <a href="/traderalign/journal-validation" title="Validation Tracker" class="<?= $currentPage === 'journal-validation' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 14l2 2 4-4"/></svg>
    </a>
    <?php else: ?>
    <a href="<?= sidebarLink('reports', $currentPage) ?>" title="Reports" class="<?= $currentPage === 'reports' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v16a2 2 0 0 0 2 2h16"/><rect x="7" y="13" width="3" height="5"/><rect x="12" y="9" width="3" height="9"/><rect x="17" y="5" width="3" height="13"/></svg>
    </a>
    <?php endif; ?>
    <a href="/traderalign/calculator" title="Calculator" class="<?= $currentPage === 'calculator' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="2" width="16" height="20" rx="2"/><line x1="8" y1="6" x2="16" y2="6"/><line x1="8" y1="10" x2="16" y2="10"/></svg>
    </a>
    <?php if (!$isValidatingNav): ?>
    <a href="/traderalign/strategy" title="Strategy" class="<?= in_array($currentPage, ['strategy', 'strategies'], true) ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4"/><line x1="12" y1="1" x2="12" y2="5"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="1" y1="12" x2="5" y2="12"/><line x1="19" y1="12" x2="23" y2="12"/></svg>
    </a>
    <?php endif; ?>
    <!-- 2026-08-12 workflow-isolation audit: the "Validate a New Strategy"
         sidebar icon (added in the earlier edge-warning pass) was moved out
         of the sidebar per explicit instruction, the sidebar is already
         full, and this entry point doesn't need equal billing with the
         primary nav. The real entry point (this same strategy-validation.php
         form, unchanged) now lives as a small, muted link in the Main
         Dashboard's page header, see dashboard.php. Nothing about the
         underlying flow changed: saving that form still flips this user's
         own workflow_state to 'validation', same as before. -->
    <a href="/traderalign/colex" title="Colex AI" class="<?= $currentPage === 'colex' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
    </a>

    <div style="flex:1"></div>
    <a href="/traderalign/settings" title="Settings" class="<?= $currentPage === 'settings' ? 'active' : '' ?>">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
    </a>
    <a href="/traderalign/api/auth/sign-out" title="Sign Out" style="margin-bottom:1rem" onclick="return traderalignSignOut(event)">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
    </a>
</nav>

<!-- 2026-08-19 security fix: sign-out is now a real POST (see index.php's
     route change + api/auth/sign-out.php) instead of a plain GET
     navigation, so it can't be triggered by a forged <img>/<a> on another
     page. The href above is kept as a plain fallback for the rare case JS
     is disabled; when JS runs, this intercepts the click and does a real
     POST (csrf.js's fetch() wrapper attaches the token automatically)
     before navigating away. -->
<script>
function traderalignSignOut(event) {
    if (event) event.preventDefault();
    fetch('/traderalign/api/auth/sign-out', { method: 'POST' })
        .catch(function () {})
        .then(function () { window.location.href = '/traderalign/sign-in'; });
    return false;
}
</script>

<?php
/* 2026-08-20: the "Carry active_strategy_id to sidebar links" client-side
   script that used to live here is retired. It relied on browser
   sessionStorage to shuttle the active strategy between pages via
   ?strategy_id= link rewriting, a mechanism that only ever caught up
   after a page had already rendered with the wrong default, never
   survived a new tab or cleared storage, and (once the real fix below
   went in) risked overriding the correct strategy with a stale stored
   value. Dashboard/Reports/Drafts now each independently resolve the
   SAME correct active strategy server-side, via a real persisted pointer
   (spGetActiveStrategyId()/spRecordActiveStrategy(), src/StrategyPicker.php,
   backed by the user_active_strategy table). Every page gets the right
   strategy on its own, regardless of which link brought the user there,
   so the sidebar no longer needs to know or carry anything about strategy
   at all. See migration_add_user_active_strategy.sql for the full
   incident writeup. */
?>

<!-- Keep user_profiles.timezone in sync with wherever the trader is
     actually logged in from right now (Intl's own live IANA zone — the
     real per-device/OS signal, changes automatically after travel), so
     every page's greeting/local-time display (Colex AI, Trader Profile)
     stays correct without the trader having to manually revisit Settings.
     Fire-and-forget, once per browser tab session — the app-wide, single
     source of truth is still the one user_profiles.timezone column; this
     only keeps that column current. -->
<script>
(function() {
    if (sessionStorage.getItem('tz_synced')) return;
    var tz;
    try {
        tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
    } catch (e) {
        return;
    }
    if (!tz) return;
    fetch('/traderalign/api/settings/sync-timezone', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ timezone: tz })
    }).then(function() {
        sessionStorage.setItem('tz_synced', '1');
    }).catch(function() {});
})();
</script>
