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

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

// Rejects email addresses, URLs, "@", numbers-only values, and a short
// list of obvious placeholder junk — accepts everything else, including
// handles like "FXHunter" or "Atlas99" (a preferred trading name is not
// required to be a legal name, just not one of these obvious non-names).
function isValidPreferredUsername(string $v): bool {
    if (mb_strlen($v) < 2) return false;
    if (strpos($v, '@') !== false) return false;
    if (preg_match('/(https?:\/\/|www\.|\.(com|net|org|io|co|xyz|info)\b)/i', $v)) return false;
    if (preg_match('/^\d+$/', $v)) return false;
    if (!preg_match('/[A-Za-z]/', $v)) return false;
    $junk = ['test', 'testing', 'asdf', 'admin', 'none', 'n/a', 'na', 'xxx', 'null', 'undefined', 'user', 'username', 'unknown', 'anonymous'];
    if (in_array(strtolower($v), $junk, true)) return false;
    return true;
}

$preferredUsername = trim($_POST['preferred_username'] ?? '');
$disciplineRating = $_POST['discipline_rating'] ?? '';
$deviationFrequency = $_POST['deviation_frequency'] ?? '';
$dominantEmotion = $_POST['dominant_emotion'] ?? '';
$hasEdge = $_POST['has_edge'] ?? '';

// Preferred Username is mandatory — this is the name TraderAlign uses
// whenever it speaks directly to the trader (Trader Profile's greeting,
// and any future module that addresses the user by name).
if ($preferredUsername === '' || !isValidPreferredUsername($preferredUsername)) {
    header('Location: /traderalign/onboarding?step=2&error=' . urlencode('Please enter a valid preferred username'));
    exit;
}
if (mb_strlen($preferredUsername) > 40) {
    $preferredUsername = mb_substr($preferredUsername, 0, 40);
}
if (empty($disciplineRating) || empty($deviationFrequency)) {
    header('Location: /traderalign/onboarding?step=2&error=' . urlencode('Please answer all required questions') . '&preferred_username=' . urlencode($preferredUsername));
    exit;
}

// Merge with existing context
$profile = $db->selectById('user_profiles', $userId, 'user_id');
$existing = json_decode($profile['onboarding_context'] ?? '{}', true) ?: [];
$ctx = array_merge($existing, [
    'discipline_rating' => $disciplineRating,
    'deviation_frequency' => $deviationFrequency,
    'dominant_emotion' => $dominantEmotion,
    'has_edge' => $hasEdge,
]);

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

// /onboarding?step=3 is a dead-end (plain links, writes nothing — see
// public/onboarding.php's own step-3 branch, now just a redirect here too).
// /onboarding-stage3 is the real, working step 3 — it's the only place that
// actually writes journey_type/workflow_state/onboarding_complete.
header('Location: /traderalign/onboarding-stage3');
exit;