<?php

class ContentSecurityPolicy {
    private array $directives = [];

    public function __construct() {
        $this->directives = [
            'default-src' => ["'self'"],
            'script-src' => ["'self'", "'unsafe-inline'"],
            'style-src' => ["'self'", "'unsafe-inline'"],
            'img-src' => ["'self'", 'data:', 'https:'],
            'font-src' => ["'self'"],
            'connect-src' => ["'self'"],
            'media-src' => ["'self'"],
            'object-src' => ["'none'"],
            'frame-src' => ["'none'"],
            'base-uri' => ["'self'"],
            'form-action' => ["'self'"]
        ];
    }

    public function addDirective(string $name, array $values): void {
        if (!isset($this->directives[$name])) {
            $this->directives[$name] = [];
        }
        $this->directives[$name] = array_merge($this->directives[$name], $values);
    }

    public function removeDirective(string $name): void {
        unset($this->directives[$name]);
    }

    public function setDirective(string $name, array $values): void {
        $this->directives[$name] = $values;
    }

    public function toHeader(): string {
        $parts = [];
        foreach ($this->directives as $directive => $values) {
            if (!empty($values)) {
                $parts[] = $directive . ' ' . implode(' ', $values);
            }
        }
        return implode('; ', $parts);
    }

    public function toMetaTag(): string {
        return '<meta http-equiv="Content-Security-Policy" content="' . htmlspecialchars($this->toHeader()) . '">';
    }
}