<?php

namespace Ignite\Core\Http\Middleware;

use Closure;

class SecureHeadersMiddleware
{
    /* Headers which you do not want in the application's
     * responses. Great starting point would be to use
     * Scott Helme's security headers test site:
     * https://securityheaders.com/
     * -------------------------------------------------- */
    private array $unwantedHeaderList = [
        'X-Powered-By',
        'Server',
    ];

    /* Returns secure headers in HTTP(S) response
     * -------------------------------------------------- */
    public function handle($request, Closure $next)
    {
        $this->removeUnwantedHeaders($this->unwantedHeaderList);
        $response = $next($request);
        if (config('core.secure_headers.show_content_security_policy')) {
            $response->headers->set('Content-Security-Policy', env('HEADER_CONTENT_SECURITY_POLICY', "style-src 'self' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"));
        }
        if (config('core.secure_headers.show_referrer_policy')) {
            $response->headers->set('Referrer-Policy', env('HEADER_REFERRER_POLICY', 'no-referrer-when-downgrade'));
        }
        if (config('core.secure_headers.show_strict_transport_security')) {
            $response->headers->set('Strict-Transport-Security', env('HEADER_STRICT_TRANSPORT_SECURITY', 'max-age:31536000; includeSubDomains'));
        }
        if (config('core.secure_headers.show_x_content_type_options')) {
            $response->headers->set('X-Content-Type-Options', env('HEADER_X_CONTENT_TYPE_OPTIONS', 'nosniff'));
        }
        if (config('core.secure_headers.show_x_frame_options')) {
            $response->headers->set('X-Frame-Options', env('HEADER_X_FRAME_OPTIONS', 'DENY'));
        }
        if (config('core.secure_headers.show_x_xss_protection')) {
            $response->headers->set('X-XSS-Protection', env('HEADER_X_XSS_PROTECTION', '1; mode=block'));
        }

        return $response;
    }

    /* Remove previously set headers (case-insensitive)
     * -------------------------------------------------- */
    private function removeUnwantedHeaders($headerList): void
    {
        foreach ($headerList as $header) {
            header_remove($header);
        }
    }
}
