<?php

namespace App\Http\Middleware;

use App\Models\Language;
use App\Services\TranslationService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class SetLocale
{
    protected $translationService;

    public function __construct(TranslationService $translationService)
    {
        $this->translationService = $translationService;
    }

    /**
     * Handle an incoming request.
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // دریافت زبان از session یا مرورگر
        $locale = session('locale', config('app.locale'));

        // دریافت مدل زبان
        $language = Language::where('code', $locale)
            ->where('is_active', true)
            ->first();

        // اگر زبان پیدا نشد، زبان پیش‌فرض را انتخاب کن
        if (! $language) {
            $language = Language::where('is_default', true)
                ->where('is_active', true)
                ->first();
        }

        if ($language) {
            app()->setLocale($language->code);
            // اشتراک گذاری جهت متن و زبان با همه viewها
            view()->share('textDirection', $language->direction);
            view()->share('currentLanguage', $language);
        } else {
            // مقدار پیش‌فرض
            app()->setLocale('fa');
            view()->share('textDirection', 'rtl');
            view()->share('currentLanguage', null);
        }

        return $next($request);
    }

    /**
     * Get browser locale
     *
     * @return string|null
     */
    protected function getBrowserLocale(Request $request)
    {
        if ($request->hasHeader('Accept-Language')) {
            $browserLocale = substr($request->header('Accept-Language'), 0, 2);

            // Check if browser locale is supported
            $language = Language::where('code', $browserLocale)
                ->where('is_active', true)
                ->first();

            if ($language) {
                return $language->code;
            }
        }

        return null;
    }
}
