<?php

namespace App\Controllers;

use Config\App;

class Landing extends BaseController
{
    public function index()
    {
        $session = session();
        $config  = config(App::class);
        $locale  = $session->get('locale');

        if (! in_array($locale, $config->supportedLocales, true)) {
            $locale = $config->defaultLocale;
            $session->set('locale', $locale);
        }

        service('request')->setLocale($locale);

        return view('landing/home', [
            'currentLocale' => $locale,
            'supportedLocales' => $config->supportedLocales,
        ]);
    }

    public function setLanguage(string $locale)
    {
        $config = config(App::class);

        if (in_array($locale, $config->supportedLocales, true)) {
            session()->set('locale', $locale);
        }

        $previous = previous_url();

        if (! is_string($previous) || $previous === '') {
            return redirect()->to(site_url('/'));
        }

        return redirect()->to($previous);
    }
}
