<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class DebugCsrf
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->isMethod('POST')) {
            $sessionToken = $request->session()->token();
            $headerToken = $request->header('X-CSRF-TOKEN');
            $xsrfToken = $request->header('X-XSRF-TOKEN');
            $inputToken = $request->input('_token');

            Log::channel('single')->info('CSRF Debug', [
                'url' => $request->url(),
                'method' => $request->method(),
                'session_token' => $sessionToken,
                'header_X-CSRF-TOKEN' => $headerToken,
                'header_X-XSRF-TOKEN' => $xsrfToken ? 'present (encrypted)' : 'not present',
                'input_token' => $inputToken,
                'tokens_match' => $sessionToken === $headerToken || $sessionToken === $inputToken,
                'session_id' => $request->session()->getId(),
            ]);
        }

        return $next($request);
    }
}
