<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class LanguageController extends Controller
{
    public static array $supportedLanguages = [
        "en",
        "ro",
        "cz",
        "de",
        "dk",
        "es",
        "fr",
        "gr",
        "hu",
        "it",
        "nl",
        "pl",
        "pt",
        "ru",
        "tr"
    ];

    public function setLanguage(string $language, Request $request): RedirectResponse
    {
        // Validate the requested language
        $validator = Validator::make(
            ['language' => $language],
            ['language' => ['required', Rule::in(self::$supportedLanguages)]]
        );
        $validated = $validator->validated();

        // Save the language preference in the session
        $request->session()->put(['language' => $validated['language']]);

        // Set a plain PHP cookie immediately (for validation rules file to access)
        setcookie('language', $validated['language'], time() + (60 * 60 * 24 * 365), '/');

        return redirect()->back();
    }
}
