<?php

namespace App\Http\Middleware;

use App\Models\Language;
use App\Models\SystemSetting;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $this->determineLocale($request);
        $language = null;

        // Validate locale exists and is active
        if ($this->isValidLocale($locale)) {
            App::setLocale($locale);
            $language = Language::where('code', $locale)->where('status', 'active')->first();

            // Store in session for guests
            if (! auth()->check()) {
                session(['locale' => $locale]);
            }
        } else {
            // Fallback to default or 'en'
            $fallback = SystemSetting::get('default_locale', 'en');
            if ($this->isValidLocale($fallback)) {
                App::setLocale($fallback);
                $language = Language::where('code', $fallback)->where('status', 'active')->first();
            } else {
                App::setLocale('en');
                $language = Language::where('code', 'en')->first();
            }
        }

        // Share text direction with all views for RTL support
        $textDirection = $language?->is_rtl ? 'rtl' : 'ltr';
        View::share('textDirection', $textDirection);

        return $next($request);
    }

    /**
     * Determine the locale based on priority chain.
     */
    protected function determineLocale(Request $request): string
    {
        // Priority 1: Authenticated user's preference
        if (auth()->check() && auth()->user()->locale) {
            return auth()->user()->locale;
        }

        // Priority 2: Session (for guests or users without preference)
        if (session()->has('locale')) {
            return session('locale');
        }

        // Priority 3: Cookie
        if ($request->cookie('locale')) {
            return $request->cookie('locale');
        }

        // Priority 4: System default
        $default = SystemSetting::get('default_locale', 'en');

        // Priority 5: Fallback to 'en'
        return $default ?: 'en';
    }

    /**
     * Check if locale is valid and active.
     */
    protected function isValidLocale(string $locale): bool
    {
        return Language::where('code', $locale)
            ->where('status', 'active')
            ->exists();
    }
}
