<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * يحدد لغة الواجهة (ar/en):
 * 1) ?lang= بالرابط (يُحفظ بالجلسة)
 * 2) لغة الجلسة المحفوظة
 * 3) الافتراضي: عربي
 */
class LocaleFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $lang = $request->getGet('lang');

        if ($lang && in_array($lang, ['ar', 'en'])) {
            session()->set('locale', $lang);
        }

        $locale = session()->get('locale') ?? 'ar';
        service('request')->setLocale($locale);
        \CodeIgniter\Config\Factories::config('App')->defaultLocale = $locale;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {}
}
