<?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=1&error=Server+error'); exit; }

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

$tradingExperience = $_POST['trading_experience'] ?? '';
$traderType = $_POST['trader_type'] ?? '';
$journaling = $_POST['journaling'] ?? '';
$biggestChallenge = $_POST['biggest_challenge'] ?? '';
$goal = trim($_POST['goal'] ?? '');

if (empty($tradingExperience) || empty($traderType)) {
    header('Location: /traderalign/onboarding?step=1&error=Please+answer+all+required+questions');
    exit;
}

// Map trader_type to valid trading_style for the CHECK constraint
$styleMap = [
    'scalper' => 'scalper',
    'day_trader' => 'day_trader',
    'swing' => 'swing',
    'position' => 'position',
    'funded_challenger' => 'day_trader',
    'funded_holder' => 'day_trader',
    'investor' => 'position',
    'beginner' => 'day_trader',
];
$tradingStyle = $styleMap[$traderType] ?? 'day_trader';

$ctx = [
    'trading_experience' => $tradingExperience,
    'trader_type' => $traderType,
    'journaling' => $journaling,
    'biggest_challenge' => $biggestChallenge,
    'goal' => $goal,
    'captured_at' => date('c'),
];

$db->update('user_profiles', $userId, [
    'trading_style' => $tradingStyle,
    'onboarding_context' => json_encode($ctx),
], 'user_id');

header('Location: /traderalign/onboarding?step=2');
exit;