<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$b = json_decode(file_get_contents('php://input'), true) ?? [];

$state = mb_substr(trim($b['state']        ?? ''), 0, 100);
$city  = mb_substr(trim($b['city']         ?? ''), 0, 100);
$hood  = mb_substr(trim($b['neighborhood'] ?? ''), 0, 100);
$edu   = $b['education_level'] ?? '';
$age   = $b['age_group']       ?? '';
$goals = mb_substr(trim($b['goals']        ?? ''), 0, 200);

// Fix 2: المسار "اقتراح" لا إجبار — المستخدم يختار نهائياً
// حساب المسار المقترح بناءً على التعليم
$suggested_track = 'foundation';
if (in_array($edu, ['university', 'graduate'])) $suggested_track = 'growth';
if (in_array($edu, ['phd', 'professor']))        $suggested_track = 'leadership';

// إذا أرسل المستخدم اختياره الصريح → نحترمه
$allowed_tracks = ['foundation', 'growth', 'leadership'];
$final_track = (isset($b['track']) && in_array($b['track'], $allowed_tracks))
    ? $b['track']
    : $suggested_track;

// إنشاء أو جلب الحي
$nhood_id = null;
if ($state && $city) {
    $ns = db()->prepare('SELECT id FROM neighborhoods WHERE name = ? AND city = ? LIMIT 1');
    $ns->execute([$hood ?: $city, $city]);
    $row = $ns->fetch();
    if (!$row) {
        db()->prepare('INSERT INTO neighborhoods (name, city, state) VALUES (?, ?, ?)')
            ->execute([$hood ?: $city, $city, $state]);
        $nhood_id = (int)db()->lastInsertId();
    } else {
        $nhood_id = (int)$row['id'];
    }
}

db()->prepare(
    'UPDATE users SET neighborhood_id=?, state=?, city=?, neighborhood=?,
     education_level=?, age_group=?, learning_track=?, goals=?, onboarding_done=1
     WHERE id=?'
)->execute([$nhood_id, $state, $city, $hood, $edu, $age, $final_track, $goals, $u['id']]);

json_response([
    'success'          => true,
    'track'            => $final_track,
    'suggested_track'  => $suggested_track,  // للعرض في الواجهة
    'track_changed'    => $final_track !== $suggested_track,
    'message'          => 'أهلاً بك في سودانا! 🇸🇩',
]);
