<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class LogFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $startTime = microtime(true);
        $request->startTime = $startTime;
        
        $requestBody = '';
        if ($request->getMethod() === 'POST') {
            $requestBody = json_encode($request->getJSON(true));
        }
        
        log_message('info', sprintf(
            '[%s] %s %s %s',
            date('Y-m-d H:i:s'),
            $request->getMethod(),
            current_url(),
            $requestBody
        ));
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        $endTime = microtime(true);
        $duration = round(($endTime - $request->startTime) * 1000, 2);
        
        $responseBody = '';
        if ($response->getStatusCode() !== 200) {
            $responseBody = $response->getBody();
        }
        
        log_message('info', sprintf(
            '[%s] %s %s %d %s %.2fms %s',
            date('Y-m-d H:i:s'),
            $request->getMethod(),
            current_url(),
            $response->getStatusCode(),
            $response->getReasonPhrase(),
            $duration,
            $responseBody
        ));
    }
} 