<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('../pages/login.php');
}

$returnTo = safe_page_return((string) ($_POST['return_to'] ?? ''), is_logged_in($conn) ? auth_preferred_landing_page($conn) : 'login.php');
$returnPath = '../pages/' . ltrim($returnTo, '/');

ensure_post_csrf_or_redirect('set_language', $returnPath);

$language = normalize_language((string) ($_POST['language'] ?? 'th'));

remember_language($language);

if ($returnTo === '') {
    $returnTo = is_logged_in($conn) ? auth_preferred_landing_page($conn) : 'login.php';
}

redirect($returnPath);
