<?php

namespace Storeplugin\PDFInvoice\Framework\Security;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Contracts\ServiceInterface;
use Storeplugin\PDFInvoice\Framework\Utils\ContentSecurityPolicy;
use Storeplugin\PDFInvoice\Config;

/**
 * Security Service
 *
 * Initializes and manages security features for the plugin.
 */
class SecurityService implements ServiceInterface
{
    /**
     * Register the service
     *
     * This is called automatically by the dependency injection container
     */
    public function register(): void
    {
        // Initialize Content Security Policy
        $this->initCSP();

        // Initialize security hooks
        $this->initSecurityHooks();
    }

    /**
     * Initialize Content Security Policy
     */
    private function initCSP(): void
    {
        // Check if CSP should be enabled
        $enableCSP = \apply_filters('nxtpdf_enable_csp', true);

        if (!$enableCSP) {
            return;
        }

        // Initialize CSP
        ContentSecurityPolicy::init();

        // Allow customization of CSP directives via filter
        \add_filter('nxtpdf_csp_directives', function ($directives) {
            // Example: You can modify directives here
            // $directives['script-src'][] = 'https://example.com';
            return $directives;
        });
    }

    /**
     * Initialize security hooks
     */
    private function initSecurityHooks(): void
    {
        // Add security headers
        \add_action('admin_init', [$this, 'addSecurityHeaders']);
    }

    /**
     * Add additional security headers
     */
    public function addSecurityHeaders(): void
    {
        // Only add headers in admin area
        if (!\is_admin()) {
            return;
        }

        // Check if on plugin pages
        if (!$this->isPluginPage()) {
            return;
        }

        // Don't send headers if already sent
        if (headers_sent()) {
            return;
        }

        // X-Content-Type-Options: Prevent MIME type sniffing
        header('X-Content-Type-Options: nosniff');

        // X-Frame-Options: Prevent clickjacking (already handled by WordPress, but reinforce)
        header('X-Frame-Options: SAMEORIGIN');

        // X-XSS-Protection: Enable browser XSS protection
        header('X-XSS-Protection: 1; mode=block');

        // Referrer-Policy: Control referrer information
        header('Referrer-Policy: strict-origin-when-cross-origin');

        // Permissions-Policy: Control browser features
        header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
    }

    /**
     * Check if current page is a plugin page
     *
     * @return bool
     */
    private function isPluginPage(): bool
    {
        global $plugin_page;

        // Check if it's a registered plugin page
        if (!empty($plugin_page) && strpos($plugin_page, Config::prefix()) !== false) {
            return true;
        }

        // Check $_GET parameter
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading current admin page slug from the URL to determine if this is a plugin page; no state change.
        if (isset($_GET['page']) && strpos(\sanitize_text_field(\wp_unslash($_GET['page'])), Config::prefix()) !== false) {
            return true;
        }

        return false;
    }
}
