<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Symfony\Component\HttpFoundation\Response;

class CheckSessionExpiration
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response) $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        if(!$request->session()->has('fair')) {
            $request->session()->flash('message_flash', "Su sesión ha caducado.");
            return $this->redirectToWelcomePage($request);
        }
        return $next($request);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Foundation\Application|Application|Redirector|RedirectResponse|JsonResponse
     */
    public function redirectToWelcomePage(Request $request): Application|\Illuminate\Foundation\Application|RedirectResponse|Redirector|JsonResponse
    {
        $redirectUrl = "?c=" . ($request->get('c') ?? $request->get('fair_code'));
        $redirectUrl .= "&lang=" . \session()->get('locale') ??  'es_ES';
        if ($request->expectsJson()) {
            return response()->json([
              'redirect_url' => $redirectUrl
            ], 200);
        }
        return redirect($redirectUrl);
    }
}
