<?php

class SecurityPolicy
{
    /**
     * CSP directives container
     * @var array
     */
    private $directives = [];

    /**
     * Add or overwrite a CSP directive
     *
     * @param string $name
     * @param string $value
     */
    public function addDirective($name, $value)
    {
        // Normalize whitespace to avoid newlines
        $value = preg_replace('/\s+/', ' ', trim($value));

        // Overwrite instead of stacking
        $this->directives[$name] = $value;
    }

    /**
     * Build a single valid CSP header string
     *
     * @return string
     */
    private function buildHeader()
    {
        $parts = [];

        foreach ($this->directives as $name => $value) {
            $parts[] = $name . ' ' . $value;
        }

        return 'Content-Security-Policy: ' . implode('; ', $parts);
    }

    /**
     * Apply CSP header safely
     */
    public function apply()
    {
        if (!headers_sent()) {
            header($this->buildHeader(), true);
        }
    }

    /**
     * Set a secure cookie (PHP 7.4 safe)
     */
    public function setSecureCookie(
        $name,
        $value,
        $expiry = 0,
        $path = '/',
        $domain = '',
        $httpOnly = true,
        $secure = true,
        $sameSite = 'Strict'
    ) {
        $cookie = urlencode($name) . '=' . urlencode($value);

        if ($expiry > 0) {
            $cookie .= '; Expires=' . gmdate('D, d-M-Y H:i:s T', $expiry);
        }

        $cookie .= '; Path=' . $path;

        if ($domain !== '') {
            $cookie .= '; Domain=' . $domain;
        }

        if ($secure) {
            $cookie .= '; Secure';
        }

        if ($httpOnly) {
            $cookie .= '; HttpOnly';
        }

        if ($sameSite) {
            $cookie .= '; SameSite=' . $sameSite;
        }

        header('Set-Cookie: ' . $cookie, false);
    }

    /**
     * Start a hardened session (PHP 7.4 compatible)
     */
    public function startSecureSession()
    {
        if (session_status() === PHP_SESSION_ACTIVE) {
            return;
        }

        session_set_cookie_params(
            0,
            '/',
            '',
            true,
            true
        );

        session_start();

        // Manually append SameSite for PHP 7.4
        header('Set-Cookie: ' . session_name() . '=' . session_id() . '; Path=/; Secure; HttpOnly; SameSite=Strict', false);

        session_regenerate_id(true);
    }
}
