<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $locale = null;

        if (Session::has('locale')) {
            $locale = (string) Session::get('locale');
        } elseif ($request->hasCookie('locale')) {
            $locale = (string) $request->cookie('locale');
        }

        if (in_array($locale, ['en', 'ar'], true)) {
            App::setLocale($locale);
            Session::put('locale', $locale);
        }

        Carbon::setLocale(App::getLocale());
        CarbonImmutable::setLocale(App::getLocale());

        $user = $request->user();
        if ($user && ! $user->is_admin && $request->is('platform/*')) {
            $user->loadMissing('employee');
            $employee = $user->employee;
            if ($employee && ! (bool) ($employee->is_active ?? true)) {
                Auth::logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();

                $message = App::getLocale() === 'ar'
                    ? 'حساب الموظف موقوف.'
                    : 'Employee account is disabled.';

                if ($request->expectsJson()) {
                    return response()->json(['message' => $message], 403);
                }

                return redirect()->route('login')->withErrors(['username' => $message]);
            }
        }

        return $next($request);
    }
}
