<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ClearSearchOnSectionChange
{
    public function handle(Request $request, Closure $next)
    {
        $section     = explode('/', trim($request->path(), '/'))[0];
        $lastSection = $request->session()->get('_last_section');

        if ($lastSection && $lastSection !== $section) {
            $request->session()->forget(['search', 'field', 'sort']);
        }

        $request->session()->put('_last_section', $section);

        return $next($request);
    }
}
