<?php
require "../config/database.php";

header("Content-Type: application/json; charset=utf-8");

$data = json_decode(file_get_contents("php://input"), true);
$lang = $data["lang"] ?? ($_GET["lang"] ?? "");

if (!in_array($lang, ["en", "sr"], true)) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_language"]);
    exit;
}

$_SESSION["lang"] = $lang;
$redirect = trim((string)($_GET["redirect"] ?? ""));
if ($redirect === "") {
    $redirect = trim((string)($data["redirect"] ?? ""));
}
if ($redirect !== "") {
    header("Location: " . $redirect);
    exit;
}
echo json_encode(["success" => true, "lang" => $lang]);
