<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class SanitizerUploader
{
    public function handle(Request $request, Closure $next)
    {
        foreach ($request->files as $_file) {
            $_file = is_array($_file) ? $_file : [$_file];
            foreach ($_file as $__file) {
                $__file = is_array($__file) ? $__file : [$__file];
                foreach($__file as $file){
                    if ($file instanceof UploadedFile) {
                        $this->sanitizeFile($file);
                    }
                }
            }
        }

        return $next($request);
    }

    protected function sanitizeFile(UploadedFile $file)
    {
        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        
        $cwFactory = new \App\Logging\CloudWatchLoggerFactory();
        $_data = [
            'process' => 'Sanitize Uploaded File',
            'status' => 'Info',
            'file_name' => $originalName,
            'extension' => $extension,
            'message' => "Sanitizing file: {$originalName}"
        ];
        $cwFactory->logger(json_encode($_data));

        if (!$file->isValid()) {
            $cwFactory = new \App\Logging\CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode([
                'process' => 'Sanitize Uploaded File',
                'status' => 'Error',
                'message' => 'Upload failed. ' . $file->getErrorMessage()
            ]));
            return;
        }

        $contents = file_get_contents($file->getPathname());

        $sanitizedContents = $this->sanitizeFileContent($contents, $extension);

        file_put_contents($file->getPathname(), $sanitizedContents);
    }


    protected function sanitizeFileContent(string $contents, string $extension): string
    {
        switch (strtolower($extension)) {
            case 'html':
            case 'htm':
            case 'svg':
            //case 'png':
                return preg_replace(['/<!--.*?-->/', '/<script.*?>(.*?)<\/script>/is', '/<.*?on\w+=".*?"/is'], '', $contents);

            case 'xml':
                return preg_replace(['/<!ENTITY.*?>/', '/<!DOCTYPE.*?>/', '/<![CDATA\[.*?\]\]>/s'], '', $contents);

            default:
                return $contents;
        }
    }
}
