<?php

namespace App\Http\Middleware;

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

/**
 * Security Headers Middleware
 * 
 * This middleware adds security headers to all HTTP responses to protect
 * against common web vulnerabilities like XSS, clickjacking, and MIME sniffing.
 */
class SecurityHeadersMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Get security configuration
        $headers = config('security.headers', []);
        $csp = config('security.content_security_policy', []);

        // X-Frame-Options: Prevents clickjacking attacks
        if (isset($headers['x_frame_options'])) {
            $response->headers->set('X-Frame-Options', $headers['x_frame_options']);
        }

        // X-Content-Type-Options: Prevents MIME sniffing
        if (isset($headers['x_content_type_options'])) {
            $response->headers->set('X-Content-Type-Options', $headers['x_content_type_options']);
        }

        // X-XSS-Protection: Enables XSS filtering
        if (isset($headers['x_xss_protection'])) {
            $response->headers->set('X-XSS-Protection', $headers['x_xss_protection']);
        }

        // Referrer-Policy: Controls referrer information
        if (isset($headers['referrer_policy'])) {
            $response->headers->set('Referrer-Policy', $headers['referrer_policy']);
        }

        // Permissions-Policy: Controls browser features
        if (isset($headers['permissions_policy'])) {
            $response->headers->set('Permissions-Policy', $headers['permissions_policy']);
        }

        // Strict-Transport-Security: Enforces HTTPS
        if ($request->secure() && isset($headers['strict_transport_security'])) {
            $response->headers->set('Strict-Transport-Security', $headers['strict_transport_security']);
        }

        // Content Security Policy
        if ($csp['enabled'] ?? false) {
            $cspHeader = $this->buildContentSecurityPolicy($csp);
            $headerName = ($csp['report_only'] ?? false) ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy';
            $response->headers->set($headerName, $cspHeader);
        }

        // Remove server information
        $response->headers->remove('Server');
        $response->headers->remove('X-Powered-By');

        return $response;
    }

    /**
     * Build Content Security Policy header value
     *
     * @param array $csp
     * @return string
     */
    private function buildContentSecurityPolicy(array $csp): string
    {
        $directives = $csp['directives'] ?? [];
        $policy = [];

        foreach ($directives as $directive => $value) {
            $policy[] = $directive . ' ' . $value;
        }

        return implode('; ', $policy);
    }
}
