<?php

namespace App\Http\Middleware;

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

class rateUpdate
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $currentRouteName = Route::currentRouteName();
        $isRateRoute = in_array($currentRouteName, [
            'admin_fit.rate.create',
            'admin_fit.rate.store',
            'admin_fit.rate.quick_store',
        ], true);

        $activeRateTodayRecord = rate::query()
            ->where('is_active', true)
            ->whereDate('created_at', now()->toDateString())
            ->latest('id')
            ->first(['id', 'usd_rate', 'created_at']);

        if ($activeRateTodayRecord) {
            View::share('rateTodayInfo', [
                'is_active_today' => true,
                'usd_rate' => (float) $activeRateTodayRecord->usd_rate,
                'created_at' => optional($activeRateTodayRecord->created_at)->format('d/m/Y H:i'),
            ]);
        }

        if (! $activeRateTodayRecord && ! $isRateRoute) {
            $returnTo = $request->fullUrl();

            View::share('rateWarning', [
                'message' => 'Debe registrar una tasa activa del dia de hoy para continuar con la operación.',
                'link' => route('admin_fit.rate.create', ['return_to' => $returnTo]),
                'link_text' => 'Agregar tasa',
                'quick_store_link' => route('admin_fit.rate.quick_store'),
                'return_to' => $returnTo,
            ]);
        } elseif (! $activeRateTodayRecord) {
            View::share('rateTodayInfo', [
                'is_active_today' => false,
                'usd_rate' => null,
                'created_at' => null,
            ]);
        }

        return $next($request);
    }
}
