<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/ScopedDb.php';
require_once __DIR__ . '/../src/Auth.php';
require_once __DIR__ . '/../src/Csrf.php';

if (session_status() === PHP_SESSION_NONE) { 
    session_name(SESSION_NAME); 
    session_start(); 
}

try {
    $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 
        PDO::ATTR_EMULATE_PREPARES => false
    ]);
} catch (PDOException $e) { 
    header('Location: /traderalign/onboarding?step=3&error=Server+error'); 
    exit; 
}

$auth = new Auth($pdo);
$userId = $auth->requireAuth();
$db = new ScopedDb($pdo, $userId);

// ── POST HANDLER — must run before any HTML output ─────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['journey_type'])) {
    $journeyType = $_POST['journey_type'];
    $validTypes = ['has_edge', 'developing_edge', 'no_edge'];
    
    if (!in_array($journeyType, $validTypes)) {
        header('Location: /traderalign/onboarding?step=3&error=Invalid+selection');
        exit;
    }

    // Preferred Username is mandatory (api/onboarding/step2.php already
    // enforces this client- and server-side on its own form) — but this
    // page is directly reachable by URL, bypassing Step 2 entirely, so
    // onboarding_complete must never be set to 1 here without confirming a
    // real name was actually saved first. Without this guard, a trader
    // could complete onboarding having never provided a name — confirmed
    // this has genuinely happened before (7 real accounts in this
    // database are onboarding_complete=1 with a NULL display_name).
    $profile = $db->selectById('user_profiles', $userId, 'user_id');
    if (empty($profile['display_name'])) {
        header('Location: /traderalign/onboarding?step=2&error=' . urlencode('Please enter a preferred username before continuing'));
        exit;
    }

    try {
        $pdo->beginTransaction();

        $existingContext = json_decode($profile['onboarding_context'] ?? '{}', true) ?: [];
        
        $updatedContext = array_merge($existingContext, [
            'journey_type' => $journeyType,
            'journey_selected_at' => date('Y-m-d H:i:s')
        ]);

        // Validation Workflow: "I'm Developing a Trading Edge" is the only
        // path that starts a user in the validation workflow context — the
        // other two (has_edge/no_edge) go straight into the main workflow.
        // workflow_state is the real, first-class "which workflow is this
        // user currently in" field (user_profiles.workflow_state) — journey_type
        // above is only ever the one-time onboarding choice and is never
        // updated again, so it can't represent current state after graduation.
        $workflowState = $journeyType === 'developing_edge' ? 'validation' : 'main';

        // validation_entry_source (2026-08-16 workflow-isolation-leakage
        // pass): 'onboarding' for this path — this user has never been in
        // the main workflow yet, so ValidationService/sidebar.php must
        // never show a "back to main workflow" link for them (there is
        // nothing real to go back to). Cleared to NULL for has_edge/no_edge
        // — not applicable outside the validation workflow.
        $validationEntrySource = $journeyType === 'developing_edge' ? 'onboarding' : null;

        $db->update('user_profiles', $userId, [
            'onboarding_context' => json_encode($updatedContext),
            'onboarding_complete' => 1,
            'workflow_state' => $workflowState,
            'validation_entry_source' => $validationEntrySource,
        ], 'user_id');
        
        $pdo->commit();
        
        // Use JavaScript redirect since PHP header() may fail if output has started
        $redirectMap = [
            'has_edge'        => '/traderalign/trading-center',
            'developing_edge' => '/traderalign/strategy-validation',
            'no_edge'         => '/traderalign/learning-center',
        ];
        $redirectUrl = $redirectMap[$journeyType] ?? '/traderalign/dashboard';
        
        echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=' . $redirectUrl . '"></head><body><script>window.location.href="' . $redirectUrl . '";</script></body></html>';
        exit;
        
    } catch (\Throwable $e) {
        $pdo->rollBack();
        header('Location: /traderalign/onboarding?step=3&error=' . urlencode($e->getMessage()));
        exit;
    }
}

$profile = $db->selectById('user_profiles', $userId, 'user_id');
$userName = htmlspecialchars(resolveDisplayName($profile));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Choose Your Path - 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>
/* ── Base ─────────────────────────────────────────── */
.dash-layout{display:flex;min-height:100vh}
.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;padding:2rem;max-width:calc(100vw - 4rem)}

/* ── Onboarding Stage 3 specific ──────────────────── */
.page-header{text-align:center;margin-bottom:2.5rem}
.page-title{font-size:1.8rem;font-weight:800;color:var(--foreground);letter-spacing:-.02em;margin-bottom:.5rem}
.page-sub{color:var(--foreground-muted);font-size:.9rem;line-height:1.5;max-width:600px;margin:0 auto}

/* Progress indicator */
.progress-bar-onboard{display:flex;align-items:center;justify-content:center;gap:0;margin-bottom:2.5rem}
.progress-step{display:flex;align-items:center;gap:.5rem}
.progress-dot{width:12px;height:12px;border-radius:50%;background:var(--background-surface);border:2px solid var(--border);transition:all .3s ease}
.progress-dot.completed{background:var(--positive);border-color:var(--positive)}
.progress-dot.active{background:var(--primary);border-color:var(--primary);box-shadow:0 0 12px color-mix(in srgb,var(--primary) 40%,transparent)}
.progress-label{font-size:.75rem;color:var(--foreground-dim);font-weight:500}
.progress-label.active{color:var(--primary);font-weight:600}
.progress-line{width:3rem;height:2px;background:var(--border);margin:0 .75rem}
.progress-line.completed{background:var(--positive)}

/* Journey cards */
.journey-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-bottom:2rem;max-width:960px;margin-left:auto;margin-right:auto}
.journey-card{background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.5rem;cursor:pointer;transition:all .2s ease;position:relative}
.journey-card:hover{border-color:color-mix(in srgb,var(--primary) 30%,transparent);transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.15)}
.journey-card.selected{border-color:var(--primary);background:color-mix(in srgb,var(--primary) 8%,transparent);box-shadow:0 0 0 2px color-mix(in srgb,var(--primary) 20%,transparent)}
.journey-card .card-icon{font-size:1.75rem;margin-bottom:.75rem;display:block}
.journey-card .card-title{font-size:1rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem;line-height:1.3}
.journey-card .card-desc{font-size:.8rem;color:var(--foreground-dim);line-height:1.6;margin-bottom:.75rem}
.journey-card .card-features{list-style:none;padding:0;display:flex;flex-direction:column;gap:.35rem}
.journey-card .card-features li{font-size:.75rem;color:var(--foreground-muted);display:flex;align-items:center;gap:.4rem}
.journey-card .card-features li::before{content:'✓';color:var(--positive);font-weight:700;font-size:.7rem}
.journey-radio{position:absolute;top:1rem;right:1rem;width:20px;height:20px;border:2px solid var(--border);border-radius:50%;display:flex;align-items:center;justify-content:center;transition:all .2s ease}
.journey-card.selected .journey-radio{border-color:var(--primary);background:var(--primary)}
.journey-card.selected .journey-radio::after{content:'';width:8px;height:8px;background:#fff;border-radius:50%}

/* Continue button */
.btn-row{text-align:center}
.btn-continue{padding:.75rem 2rem;border-radius:var(--radius-lg);font-size:.9rem;font-weight:600;color:#fff;background:var(--primary);border:none;cursor:pointer;transition:all .2s ease;font-family:var(--font-sans);min-width:200px}
.btn-continue:hover{opacity:.9;transform:translateY(-1px)}
.btn-continue:disabled{background:var(--background-surface);color:var(--foreground-dim);cursor:not-allowed;transform:none}
.btn-hint{font-size:.75rem;color:var(--foreground-dim);margin-top:.5rem}

@media(max-width:768px){
  .main{padding:1rem}
  .journey-grid{grid-template-columns:1fr;max-width:100%}
  .progress-line{width:1.5rem;margin:0 .5rem}
}
</style>
</head>
<body class="dash-layout">

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

<main class="main">

<div class="page-header">
    <h1 class="page-title">Welcome, <?= $userName ?> 👋</h1>
    <p class="page-sub">Where are you on your trading journey? Choose the path that best describes your current situation, and we'll tailor TraderAlign to support you.</p>
</div>

<!-- Progress Indicator -->
<div class="progress-bar-onboard">
    <div class="progress-step">
        <div class="progress-dot completed"></div>
        <span class="progress-label">Profile</span>
    </div>
    <div class="progress-line completed"></div>
    <div class="progress-step">
        <div class="progress-dot completed"></div>
        <span class="progress-label">Trading Style</span>
    </div>
    <div class="progress-line completed"></div>
    <div class="progress-step">
        <div class="progress-dot active"></div>
        <span class="progress-label active">Your Path</span>
    </div>
</div>

<!-- Journey Cards -->
<form method="POST" action="/traderalign/onboarding-stage3" id="journey-form">
    <?= Csrf::field() ?>
    <div class="journey-grid">
        <!-- Card 1: Already Have an Edge -->
        <div class="journey-card" data-journey="has_edge" onclick="selectJourney('has_edge', this)">
            <div class="journey-radio"></div>
            <span class="card-icon">📈</span>
            <h3 class="card-title">I Already Have a Trading Edge</h3>
            <p class="card-desc">You have a proven strategy and consistent results. Jump right into tracking, journaling, and optimizing your performance.</p>
            <ul class="card-features">
                <li>Track live performance</li>
                <li>Advanced journaling</li>
                <li>Strategy optimization</li>
            </ul>
        </div>

        <!-- Card 2: Developing an Edge -->
        <div class="journey-card" data-journey="developing_edge" onclick="selectJourney('developing_edge', this)">
            <div class="journey-radio"></div>
            <span class="card-icon">🔬</span>
            <h3 class="card-title">I'm Developing a Trading Edge</h3>
            <p class="card-desc">You're actively working on your strategy and testing ideas. Use our validation tools to build and refine your edge systematically.</p>
            <ul class="card-features">
                <li>Strategy builder</li>
                <li>Backtesting suite</li>
                <li>Validation tracking</li>
            </ul>
        </div>

        <!-- Card 3: Don't Have an Edge Yet -->
        <div class="journey-card" data-journey="no_edge" onclick="selectJourney('no_edge', this)">
            <div class="journey-radio"></div>
            <span class="card-icon">📚</span>
            <h3 class="card-title">I Don't Yet Have a Trading Edge</h3>
            <p class="card-desc">You're new to trading or still learning the fundamentals. Start with our educational resources to build a strong foundation.</p>
            <ul class="card-features">
                <li>Trading fundamentals</li>
                <li>Structured learning paths</li>
                <li>Community support</li>
            </ul>
        </div>
    </div>

    <input type="hidden" name="journey_type" id="journey-type-input" value="">

    <div class="btn-row">
        <button type="submit" class="btn-continue" id="continue-btn" disabled>Continue</button>
        <p class="btn-hint">Select your current trading stage to continue</p>
    </div>
</form>

</main>

<script>
let selectedJourney = null;

function selectJourney(type, card) {
    // Remove selected from all cards
    document.querySelectorAll('.journey-card').forEach(function(c) {
        c.classList.remove('selected');
    });
    
    // Add selected to clicked card
    card.classList.add('selected');
    
    // Update hidden input
    document.getElementById('journey-type-input').value = type;
    selectedJourney = type;
    
    // Enable continue button
    var btn = document.getElementById('continue-btn');
    btn.disabled = false;
}

// Form validation before submit
document.getElementById('journey-form').addEventListener('submit', function(e) {
    if (!selectedJourney) {
        e.preventDefault();
        return false;
    }
    // Allow form to submit — PHP handler at top of file will process and redirect
    return true;
});
</script>

</body>
</html>