<?php

namespace Core\System;

class SecurityHeadersMiddleware
{
    public function handle(): void
    {
        if (headers_sent()) {
            return;
        }

        $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (($_SERVER['SERVER_PORT'] ?? null) == 443)
            || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';

        header('X-Frame-Options: SAMEORIGIN');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header('Permissions-Policy: accelerometer=(), autoplay=*, camera=*, display-capture=*, microphone=*, clipboard-read=*, clipboard-write=*, geolocation=(), payment=(), usb=()');
        header('Cross-Origin-Opener-Policy: same-origin');
        header('Cross-Origin-Resource-Policy: same-origin');

        $csp = [
            "default-src 'self'",
            "base-uri 'self'",
            "form-action 'self'",
            "frame-ancestors 'self'",
            "object-src 'none'",
            "frame-src 'self' https:",
            // img: allow same-origin + data URIs (thumbnails) + any HTTPS (CDN product images)
            "img-src 'self' data: https:",
            // fonts: Google Fonts + jsDelivr
            "font-src 'self' data: https://fonts.gstatic.com https://cdn.jsdelivr.net",
            // styles: unsafe-inline required for CKEditor / inline admin styles
            "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net",
            // scripts: unsafe-inline required for inline admin JS; unsafe-eval removed
            // Trusted external scripts limited to CDN + analytics only
            "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://www.googletagmanager.com https://connect.facebook.net",
            // media: allow same-origin product audio/video
            "media-src 'self' https: blob: data:",
            // connect: allow API calls to same origin and HTTPS endpoints (AI proxy, shipping APIs)
            "connect-src 'self' https:",
            "upgrade-insecure-requests",
        ];

        header('Content-Security-Policy: ' . implode('; ', $csp));

        if ($isHttps) {
            header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
        }
    }
}
