<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/User.php';

$allowedRegions = array_merge(['global'], is_string(SUPPORTED_REGIONS) ? unserialize(SUPPORTED_REGIONS) : ['usa','europe','africa']);

$region = strtolower(trim($_POST['region'] ?? ''));
if (!$region || !in_array($region, $allowedRegions, true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid region']);
    exit;
}

// Persist in session
$_SESSION['region'] = $region;

// If user is logged in, persist in their profile
if (!empty($_SESSION['user_id'])) {
    $user = new User();
    try {
        $user->updateProfile((int)$_SESSION['user_id'], ['region' => $region]);
    } catch (Exception $e) {
        // Non-fatal — just ignore persistence failure
        // but return success to client since session is set
    }
}

echo json_encode(['success' => true, 'region' => $region]);
exit;
