<?php

namespace App\Http\Middleware;

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

class LogRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Proceed to the next middleware/handler
        $response = $next($request);

        // Create a date-wise log file for every request
        $this->logRequest($request, $response);

        return $response;
    }

    /**
     * Log the request details in a date-wise log file.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function logRequest(Request $request, $response)
    {   
        if($response->status() != 200){
            // Get the current date
            $date = now()->format('Y-m-d');
            // Define the log file path
            $logPath = storage_path("logs/requests/{$date}.log");
    
            // Create the directory if it does not exist
            if (!File::exists(storage_path('logs/requests'))) {
                File::makeDirectory(storage_path('logs/requests'), 0755, true);
            }
    
            // Log the request information
            $logData = [
                'ip'       => $request->ip(),
                'method'   => $request->method(),
                'url'      => $request->fullUrl(),
                'payload'  => $request->all(),
                'user_agent' => $request->header('User-Agent'),
                'timestamp' => now()->toDateTimeString(),
            ];
    
            // Add response data to the log
            $logData['response_status'] = $response->status();
            $logData['response_content'] = $response->getContent();
            File::append($logPath, json_encode($logData) . PHP_EOL);
            // Append to the log file
        }
    }
}

