<?php
/// file: app/Controllers/LocaleController.php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;

final class LocaleController extends Controller
{
    public function switch(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            return $this->redirect(url('/'));
        }
        $locale = $request->input('locale', 'en');
        if (! in_array($locale, ['en', 'tr'], true)) {
            $locale = 'en';
        }
        Session::set('locale', $locale);
        $back = $request->input('redirect', '/');
        if (! is_string($back) || ! str_starts_with($back, '/')) {
            $back = '/';
        }
        return $this->redirect(url($back));
    }
}
