<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LogSitemapRequest
{
    public function handle(Request $request, Closure $next)
    {
        if (stripos($request->path(), 'sitemap') !== false) {
            Log::channel('seo')->info('Sitemap HTTP request', [
                'uri' => $request->getRequestUri(),
                'path' => $request->path(),
                'query' => $request->getQueryString(),
                'method' => $request->method(),
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'static_file_exists' => file_exists(public_path('sitemap.xml')),
                'static_file_size' => file_exists(public_path('sitemap.xml')) ? filesize(public_path('sitemap.xml')) : 0,
            ]);
        }

        $response = $next($request);

        if (stripos($request->path(), 'sitemap') !== false) {
            Log::channel('seo')->info('Sitemap HTTP response', [
                'uri' => $request->getRequestUri(),
                'status' => $response->getStatusCode(),
                'content_type' => $response->headers->get('Content-Type'),
                'content_length' => $response->headers->get('Content-Length'),
                'x_sitemap_source' => $response->headers->get('X-Sitemap-Source'),
            ]);
        }

        return $response;
    }
}
