<?php

namespace App\Filters;

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

class SanitizeInputFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        helper('security');

        $sanitizedGet = sanitize_request_value($request->getGet() ?? []);
        $sanitizedPost = sanitize_request_value($request->getPost() ?? []);
        $request->setGlobal('get', $sanitizedGet);
        $request->setGlobal('post', $sanitizedPost);
        $request->setGlobal('request', array_merge(is_array($sanitizedGet) ? $sanitizedGet : [], is_array($sanitizedPost) ? $sanitizedPost : []));
        $request->setGlobal('cookie', sanitize_request_value($request->getCookie() ?? []));

        $contentType = strtolower($request->getHeaderLine('Content-Type'));
        $body = $request->getBody();

        if (str_contains($contentType, 'application/json') && trim($body) !== '') {
            $decoded = json_decode($body, true);

            if (json_last_error() !== JSON_ERROR_NONE || ! is_array($decoded)) {
                return Services::response()
                    ->setStatusCode(400)
                    ->setJSON([
                        'status' => false,
                        'message' => 'Malformed JSON payload.',
                    ]);
            }

            $request->setBody((string) json_encode(sanitize_request_value($decoded), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        }

        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        return $response;
    }
}
