<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckContentType
{
    protected $allowedContentTypes = [
        'application/json',
        'application/x-www-form-urlencoded',
        'multipart/form-data',
        'text/plain',
        'text/html',
    ];

    public function handle(Request $request, Closure $next): Response
    {
        if ($request->isMethod('GET')) {
            return $next($request);
        }

        $contentType = $request->header('Content-Type');

        if (empty($contentType)) {
            abort(400, 'نوع محتوا مشخص نشده است.');
        }

        // Extract the base content type without parameters
        $baseContentType = strtolower(explode(';', $contentType)[0]);

        if (! in_array($baseContentType, $this->allowedContentTypes)) {
            abort(415, 'نوع محتوای ارسالی پشتیبانی نمی‌شود.');
        }

        // Check for suspicious content types
        if ($this->isSuspiciousContentType($contentType)) {
            abort(415, 'نوع محتوای ارسالی مشکوک است.');
        }

        return $next($request);
    }

    protected function isSuspiciousContentType(string $contentType): bool
    {
        $suspiciousPatterns = [
            '/application\/x-php/i',
            '/application\/x-httpd-php/i',
            '/application\/x-asp/i',
            '/application\/x-jsp/i',
            '/application\/x-shellscript/i',
            '/application\/x-executable/i',
            '/application\/x-shockwave-flash/i',
            '/application\/x-dosexec/i',
            '/application\/x-msdownload/i',
            '/application\/x-msdos-program/i',
        ];

        foreach ($suspiciousPatterns as $pattern) {
            if (preg_match($pattern, $contentType)) {
                return true;
            }
        }

        return false;
    }
}
