<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPageSlug
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request):Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $slug = $request->route('slug');

        $publicPath = public_path($slug);

        if (file_exists($publicPath) && is_file($publicPath) && pathinfo($slug, PATHINFO_EXTENSION) === 'php') {
            ob_start();
            include $publicPath;
            $content = ob_get_clean();
            ob_flush();

            return response($content);
        }

        if (file_exists($publicPath) && is_file($publicPath)) {
            return response()->file($publicPath);
        }

        abort_if(is_dir($publicPath), 404);

        return $next($request);
    }
}
