<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../src/ScopedDb.php';
require_once __DIR__ . '/../../src/Auth.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);

// Handle journey selection
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
    // endpoint 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) ?: [];
        
        // Update onboarding context with journey choice
        $updatedContext = array_merge($existingContext, [
            'journey_type' => $journeyType,
            'journey_selected_at' => date('Y-m-d H:i:s')
        ]);
        
        // Update user profile
        $db->update('user_profiles', $userId, [
            'onboarding_context' => json_encode($updatedContext),
            'onboarding_complete' => 1
        ], 'user_id');
        
        $pdo->commit();
        
        // Redirect based on journey type
        switch ($journeyType) {
            case 'has_edge':
                header('Location: /traderalign/dashboard');
                break;
            case 'developing_edge':
                header('Location: /traderalign/strategies/create?from=onboarding');
                break;
            case 'no_edge':
                header('Location: /traderalign/learning-center');
                break;
        }
        exit;
        
    } catch (\Throwable $e) {
        $pdo->rollBack();
        header('Location: /traderalign/onboarding?step=3&error=' . urlencode($e->getMessage()));
        exit;
    }
}

// Get current user profile for display
$profile = $db->selectById('user_profiles', $userId, 'user_id');
$userName = htmlspecialchars($profile['display_name'] ?? 'Trader');
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Choose Your Path - TraderAlign</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        brand: {
                            50: '#f0f7ff',
                            100: '#e0effe',
                            200: '#b9dffd',
                            300: '#7cc5fc',
                            400: '#36a9f8',
                            500: '#0c8ee7',
                            600: '#0070c4',
                            700: '#01599f',
                            800: '#064b83',
                            900: '#0b3f6d',
                            950: '#072849',
                        }
                    }
                }
            }
        }
    </script>
    <style>
        body {
            background-color: #0f172a;
            color: #e2e8f0;
        }
        
        .journey-card {
            background: linear-gradient(145deg, #1e293b 0%, #1a2332 100%);
            border: 1px solid #2d3a4a;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .journey-card:hover {
            border-color: #3b82f6;
            transform: translateY(-4px);
            box-shadow: 0 20px 40px -12px rgba(59, 130, 246, 0.15);
            background: linear-gradient(145deg, #1e293b 0%, #1e3a5f 100%);
        }
        
        .journey-card.selected {
            border-color: #3b82f6;
            background: linear-gradient(145deg, #1e3a5f 0%, #1a2744 100%);
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2), 0 20px 40px -12px rgba(59, 130, 246, 0.2);
        }
        
        .progress-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #334155;
            transition: all 0.3s ease;
        }
        
        .progress-dot.active {
            background-color: #3b82f6;
            box-shadow: 0 0 12px rgba(59, 130, 246, 0.5);
        }
        
        .progress-dot.completed {
            background-color: #10b981;
        }
        
        .progress-line {
            height: 2px;
            background-color: #334155;
            transition: all 0.3s ease;
        }
        
        .progress-line.active {
            background-color: #10b981;
        }
        
        .icon-container {
            width: 64px;
            height: 64px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1rem;
        }
        
        .journey-radio {
            appearance: none;
            -webkit-appearance: none;
            width: 20px;
            height: 20px;
            border: 2px solid #4b5563;
            border-radius: 50%;
            margin-right: 0;
            position: relative;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .journey-radio:checked {
            border-color: #3b82f6;
            background-color: #3b82f6;
        }
        
        .journey-radio:checked::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 8px;
            height: 8px;
            background-color: white;
            border-radius: 50%;
        }
    </style>
</head>
<body class="min-h-screen flex">
    <!-- Sidebar -->
    <?php include __DIR__ . '/../../includes/sidebar.php'; ?>
    
    <!-- Main Content -->
    <div class="flex-1 ml-64">
        <div class="max-w-4xl mx-auto px-8 py-12">
            <!-- Progress Indicator -->
            <div class="flex items-center justify-center mb-12 space-x-4">
                <div class="flex items-center">
                    <div class="progress-dot completed"></div>
                    <span class="ml-2 text-sm text-gray-400">Profile</span>
                </div>
                <div class="progress-line active w-16"></div>
                <div class="flex items-center">
                    <div class="progress-dot completed"></div>
                    <span class="ml-2 text-sm text-gray-400">Trading Style</span>
                </div>
                <div class="progress-line active w-16"></div>
                <div class="flex items-center">
                    <div class="progress-dot active"></div>
                    <span class="ml-2 text-sm text-blue-400 font-medium">Your Path</span>
                </div>
            </div>
            
            <!-- Header -->
            <div class="text-center mb-12">
                <h1 class="text-3xl font-bold text-white mb-3">
                    Welcome, <?php echo $userName; ?> 👋
                </h1>
                <p class="text-lg text-gray-400 max-w-2xl mx-auto">
                    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>
            
            <!-- Journey Cards -->
            <form method="POST" id="journey-form">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
                    <!-- Card 1: Already Have an Edge -->
                    <label class="journey-card rounded-2xl p-8 cursor-pointer relative" for="has_edge">
                        <input type="radio" name="journey_type" value="has_edge" id="has_edge" class="journey-radio absolute top-6 right-6">
                        <div class="icon-container bg-blue-500/10">
                            <svg class="w-8 h-8 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
                            </svg>
                        </div>
                        <h3 class="text-xl font-semibold text-white mb-3">I Already Have a Trading Edge</h3>
                        <p class="text-gray-400 text-sm leading-relaxed mb-4">
                            You have a proven strategy and consistent results. Jump right into tracking, 
                            journaling, and optimizing your performance.
                        </p>
                        <ul class="space-y-2">
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-green-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Track live performance
                            </li>
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-green-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Advanced journaling
                            </li>
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-green-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Strategy optimization
                            </li>
                        </ul>
                    </label>
                    
                    <!-- Card 2: Developing an Edge -->
                    <label class="journey-card rounded-2xl p-8 cursor-pointer relative" for="developing_edge">
                        <input type="radio" name="journey_type" value="developing_edge" id="developing_edge" class="journey-radio absolute top-6 right-6">
                        <div class="icon-container bg-purple-500/10">
                            <svg class="w-8 h-8 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
                            </svg>
                        </div>
                        <h3 class="text-xl font-semibold text-white mb-3">I'm Developing a Trading Edge</h3>
                        <p class="text-gray-400 text-sm leading-relaxed mb-4">
                            You're actively working on your strategy and testing ideas. Use our validation tools 
                            to build and refine your edge systematically.
                        </p>
                        <ul class="space-y-2">
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-purple-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Strategy builder
                            </li>
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-purple-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Backtesting suite
                            </li>
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-purple-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Validation tracking
                            </li>
                        </ul>
                    </label>
                    
                    <!-- Card 3: Don't Have an Edge Yet -->
                    <label class="journey-card rounded-2xl p-8 cursor-pointer relative" for="no_edge">
                        <input type="radio" name="journey_type" value="no_edge" id="no_edge" class="journey-radio absolute top-6 right-6">
                        <div class="icon-container bg-emerald-500/10">
                            <svg class="w-8 h-8 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                            </svg>
                        </div>
                        <h3 class="text-xl font-semibold text-white mb-3">I Don't Yet Have a Trading Edge</h3>
                        <p class="text-gray-400 text-sm leading-relaxed mb-4">
                            You're new to trading or still learning the fundamentals. Start with our educational 
                            resources to build a strong foundation.
                        </p>
                        <ul class="space-y-2">
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-emerald-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Trading fundamentals
                            </li>
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-emerald-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Structured learning paths
                            </li>
                            <li class="flex items-center text-sm text-gray-300">
                                <svg class="w-4 h-4 text-emerald-400 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                </svg>
                                Community support
                            </li>
                        </ul>
                    </label>
                </div>
                
                <!-- Action Button -->
                <div class="text-center">
                    <button type="submit" id="continue-btn" disabled
                        class="px-8 py-4 bg-gray-700 text-gray-400 rounded-xl font-semibold text-lg transition-all duration-300 cursor-not-allowed"
                        style="min-width: 200px;">
                        Continue
                    </button>
                    <p class="text-sm text-gray-500 mt-4">
                        Select your current trading stage to continue
                    </p>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // Handle card selection and button state
        document.addEventListener('DOMContentLoaded', function() {
            const radioButtons = document.querySelectorAll('input[name="journey_type"]');
            const continueBtn = document.getElementById('continue-btn');
            const cards = document.querySelectorAll('.journey-card');
            
            function updateButtonState() {
                const selected = document.querySelector('input[name="journey_type"]:checked');
                if (selected) {
                    continueBtn.disabled = false;
                    continueBtn.className = 'px-8 py-4 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-semibold text-lg transition-all duration-300 shadow-lg hover:shadow-blue-500/25 cursor-pointer';
                    continueBtn.style.minWidth = '200px';
                } else {
                    continueBtn.disabled = true;
                    continueBtn.className = 'px-8 py-4 bg-gray-700 text-gray-400 rounded-xl font-semibold text-lg transition-all duration-300 cursor-not-allowed';
                    continueBtn.style.minWidth = '200px';
                }
            }
            
            // Handle radio button changes
            radioButtons.forEach(radio => {
                radio.addEventListener('change', function() {
                    // Remove selected class from all cards
                    cards.forEach(card => card.classList.remove('selected'));
                    
                    // Add selected class to parent card
                    if (this.checked) {
                        this.closest('.journey-card').classList.add('selected');
                    }
                    
                    updateButtonState();
                });
            });
            
            // Allow clicking anywhere on the card to select
            cards.forEach(card => {
                card.addEventListener('click', function(e) {
                    // Don't trigger if clicking the radio button itself (already handled)
                    if (e.target.tagName === 'INPUT') return;
                    
                    const radio = this.querySelector('input[type="radio"]');
                    radio.checked = true;
                    
                    // Trigger change event
                    const event = new Event('change');
                    radio.dispatchEvent(event);
                });
            });
            
            // Initial state
            updateButtonState();
        });
    </script>
</body>
</html>