<?php
// language.php
require_once __DIR__ . '/db/db_connection.php'; 

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$new_lang = filter_input(INPUT_GET, 'lang', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$lang_dir = __DIR__ . '/core/lang/' . $new_lang;

if ($new_lang && (is_dir($lang_dir) || $new_lang === 'main')) {
    
    $_SESSION['lang'] = $new_lang;

    if (!empty($_SESSION['user_id'])) {
        try {
            $stmt = $pdo->prepare("UPDATE users SET language = :lang WHERE user_id = :uid");
            $stmt->execute([
                ':lang' => $new_lang,
                ':uid'  => $_SESSION['user_id']
            ]);
        } catch (Exception $e) {
            error_log("Error guardando idioma: " . $e->getMessage());
        }
    }
}

$redirect_url = $_SERVER['HTTP_REFERER'] ?? 'dashboard.php';
header("Location: $redirect_url");
exit;
?>