<?php
/**
 * SecurityHeadersPage — Security Headers settings and live test page.
 *
 * Tabs:
 *   Standard     — X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy
 *   HSTS         — Strict-Transport-Security with max-age, subdomains, preload
 *   Permissions  — Permissions-Policy for camera, mic, geo, payment, USB, fullscreen, autoplay
 *   Advanced     — COOP, COEP, Content-Security-Policy (report-only mode)
 *
 * @package UltraguardPro\modules\security_headers\pages
 */

namespace UltraguardPro\modules\security_headers\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class SecurityHeadersPage extends BasePage {

    protected string $ajax_nonce_action = 'ultraguard_admin_nonce';

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
    }

    public function get_scheme( $context ): array {
        $s = fn( string $k, $d = null ) => $this->get_setting( 'headers_' . $k, $d );

        $referrer_options = [
            'no-referrer'                     => 'no-referrer',
            'no-referrer-when-downgrade'      => 'no-referrer-when-downgrade',
            'origin'                          => 'origin',
            'origin-when-cross-origin'        => 'origin-when-cross-origin',
            'same-origin'                     => 'same-origin',
            'strict-origin'                   => 'strict-origin',
            'strict-origin-when-cross-origin' => 'strict-origin-when-cross-origin (recommended)',
            'unsafe-url'                      => 'unsafe-url',
        ];

        $xframe_options = [
            'SAMEORIGIN' => 'SAMEORIGIN (recommended)',
            'DENY'       => 'DENY',
        ];

        $coop_options = [
            'unsafe-none'              => 'unsafe-none',
            'same-origin-allow-popups' => 'same-origin-allow-popups',
            'same-origin'              => 'same-origin (strictest)',
        ];

        $coep_options = [
            'unsafe-none'    => 'unsafe-none',
            'require-corp'   => 'require-corp',
            'credentialless' => 'credentialless',
        ];

        $permissions_options = [
            '()'     => '() — blocked for all',
            '(self)' => '(self) — current site only',
            '*'      => '* — allowed for all (not recommended)',
        ];

        return apply_filters( 'ultraguard_security_headers_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-security-headers',
            'page_slug' => 'security-headers',
            'class'     => 'ultraguard-security-headers-page',

            'header' => [
                'title'    => __( 'Security Headers', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure HTTP security response headers to protect visitors from XSS, clickjacking, MIME sniffing and data leakage.', 'ultraguard-security-suite' ),
                'badge'    => [
                    'text'       => $this->enabled_count_badge(),
                    'badge_type' => $this->enabled_count() > 5 ? 'success' : ( $this->enabled_count() > 2 ? 'warning' : 'danger' ),
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Test Live Headers', 'ultraguard-security-suite' ), 'ultraguard_headers_test',    [], 'secondary', 'dashicons-search'     ),
                    $this->create_ajax_button( __( 'Preview Headers',   'ultraguard-security-suite' ), 'ultraguard_headers_preview', [], 'secondary', 'dashicons-visibility' ),
                    $this->create_ajax_button( __( 'Apply Recommended', 'ultraguard-security-suite' ), 'ultraguard_headers_reset',   [], 'primary',   'dashicons-shield',
                        __( 'Reset to recommended header defaults?', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [ [
                'type' => 'tabs',
                'id'   => 'security-headers-tabs',
                'tabs' => [

                    // ── Tab 1: Standard ──────────────────────────────────
                    [
                        'id'    => 'standard',
                        'title' => __( 'Standard', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-shield',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Standard Security Headers', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-shield',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'headers_xframe_enabled',
                                          'label' => __( 'X-Frame-Options', 'ultraguard-security-suite' ),
                                          'description' => __( 'Prevents clickjacking by controlling whether the site can be embedded in iframes.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'xframe_enabled', true ) ],
                                        [ 'type' => 'select', 'name' => 'headers_xframe_value',
                                          'label' => __( 'X-Frame-Options value', 'ultraguard-security-suite' ),
                                          'options' => $xframe_options,
                                          'default' => $s( 'xframe_value', 'SAMEORIGIN' ) ],

                                        [ 'type' => 'toggle', 'name' => 'headers_xcontent_type_enabled',
                                          'label' => __( 'X-Content-Type-Options: nosniff', 'ultraguard-security-suite' ),
                                          'description' => __( 'Prevents browsers from MIME-sniffing a response away from the declared content-type.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'xcontent_type_enabled', true ) ],

                                        [ 'type' => 'toggle', 'name' => 'headers_xxss_enabled',
                                          'label' => __( 'X-XSS-Protection: 1; mode=block', 'ultraguard-security-suite' ),
                                          'description' => __( 'Enables the cross-site scripting filter in older browsers. Modern browsers use CSP instead.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'xxss_enabled', true ) ],

                                        [ 'type' => 'toggle', 'name' => 'headers_referrer_policy_enabled',
                                          'label' => __( 'Referrer-Policy', 'ultraguard-security-suite' ),
                                          'description' => __( 'Controls how much referrer information is sent with requests.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'referrer_policy_enabled', true ) ],
                                        [ 'type' => 'select', 'name' => 'headers_referrer_policy_value',
                                          'label' => __( 'Referrer-Policy value', 'ultraguard-security-suite' ),
                                          'options' => $referrer_options,
                                          'default' => $s( 'referrer_policy_value', 'strict-origin-when-cross-origin' ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 2: HSTS ──────────────────────────────────────
                    [
                        'id'    => 'hsts',
                        'title' => __( 'HSTS', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-site-alt3',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'HTTP Strict Transport Security (HSTS)', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-site-alt3',
                                    'data'  => [
                                        [ 'type' => 'alert-box', 'alert_type' => 'info', 'icon' => 'dashicons-info',
                                          'message' => __( 'HSTS forces browsers to use HTTPS. Only enable this if your site has a valid SSL certificate. Once enabled, it is very hard to undo!', 'ultraguard-security-suite' ) ],
                                        [ 'type' => 'toggle', 'name' => 'headers_hsts_enabled',
                                          'label' => __( 'Enable HSTS', 'ultraguard-security-suite' ),
                                          'description' => __( 'Sends Strict-Transport-Security header. Only works over HTTPS.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'hsts_enabled', false ) ],
                                        [ 'type' => 'number', 'name' => 'headers_hsts_max_age',
                                          'label' => __( 'Max-Age (seconds)', 'ultraguard-security-suite' ),
                                          'description' => __( 'How long the browser should remember to use HTTPS. 31536000 = 1 year.', 'ultraguard-security-suite' ),
                                          'min' => 300, 'max' => 63072000, 'default' => (int) $s( 'hsts_max_age', 31536000 ) ],
                                        [ 'type' => 'toggle', 'name' => 'headers_hsts_include_subdomains',
                                          'label' => __( 'Include Subdomains', 'ultraguard-security-suite' ),
                                          'description' => __( 'Apply HSTS to all subdomains.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'hsts_include_subdomains', true ) ],
                                        [ 'type' => 'toggle', 'name' => 'headers_hsts_preload',
                                          'label' => __( 'Preload', 'ultraguard-security-suite' ),
                                          'description' => __( 'Submit your site to the browser preload list. Requires includeSubDomains and max-age ≥ 1 year.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'hsts_preload', false ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 3: Permissions ───────────────────────────────
                    [
                        'id'    => 'permissions',
                        'title' => __( 'Permissions', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-generic',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Permissions-Policy', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-generic',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'headers_permissions_policy_enabled',
                                          'label' => __( 'Enable Permissions-Policy', 'ultraguard-security-suite' ),
                                          'description' => __( 'Controls browser features like camera, microphone and geolocation.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'permissions_policy_enabled', true ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_camera',      'label' => __( 'Camera',      'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_camera', '()' ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_microphone',  'label' => __( 'Microphone',  'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_microphone', '()' ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_geolocation', 'label' => __( 'Geolocation', 'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_geolocation', '()' ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_payment',     'label' => __( 'Payment',     'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_payment', '(self)' ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_usb',         'label' => __( 'USB',         'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_usb', '()' ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_fullscreen',  'label' => __( 'Fullscreen',  'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_fullscreen', '(self)' ) ],
                                        [ 'type' => 'select', 'name' => 'headers_permissions_autoplay',    'label' => __( 'Autoplay',    'ultraguard-security-suite' ), 'options' => $permissions_options, 'default' => $s( 'permissions_autoplay', '(self)' ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 4: Advanced ──────────────────────────────────
                    [
                        'id'    => 'advanced',
                        'title' => __( 'Advanced', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-editor-code',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Advanced Headers (COOP / COEP / CSP)', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-editor-code',
                                    'data'  => [
                                        [ 'type' => 'alert-box', 'alert_type' => 'warning', 'icon' => 'dashicons-warning',
                                          'message' => __( 'COEP and a restrictive CSP can break your site. Test thoroughly in report-only mode first.', 'ultraguard-security-suite' ) ],

                                        [ 'type' => 'toggle', 'name' => 'headers_coop_enabled',
                                          'label' => __( 'Cross-Origin-Opener-Policy (COOP)', 'ultraguard-security-suite' ),
                                          'description' => __( 'Prevents cross-origin windows from gaining access to your window object.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'coop_enabled', false ) ],
                                        [ 'type' => 'select', 'name' => 'headers_coop_value',
                                          'label' => __( 'COOP value', 'ultraguard-security-suite' ),
                                          'options' => $coop_options,
                                          'default' => $s( 'coop_value', 'same-origin' ) ],

                                        [ 'type' => 'toggle', 'name' => 'headers_coep_enabled',
                                          'label' => __( 'Cross-Origin-Embedder-Policy (COEP)', 'ultraguard-security-suite' ),
                                          'description' => __( 'Prevents documents from loading cross-origin resources that don\'t grant explicit permission.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'coep_enabled', false ) ],
                                        [ 'type' => 'select', 'name' => 'headers_coep_value',
                                          'label' => __( 'COEP value', 'ultraguard-security-suite' ),
                                          'options' => $coep_options,
                                          'default' => $s( 'coep_value', 'require-corp' ) ],

                                        [ 'type' => 'toggle', 'name' => 'headers_csp_enabled',
                                          'label' => __( 'Content-Security-Policy (CSP)', 'ultraguard-security-suite' ),
                                          'description' => __( 'Define which content sources are allowed to be loaded.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'csp_enabled', false ) ],
                                        [ 'type' => 'toggle', 'name' => 'headers_csp_report_only',
                                          'label' => __( 'CSP Report-Only mode', 'ultraguard-security-suite' ),
                                          'description' => __( 'Send as Content-Security-Policy-Report-Only (doesn\'t block, just reports). Use when testing.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'csp_report_only', true ) ],
                                        [ 'type' => 'textarea', 'name' => 'headers_csp_value',
                                          'label' => __( 'CSP Directives', 'ultraguard-security-suite' ),
                                          'description' => __( 'Example: default-src \'self\'; script-src \'self\' \'unsafe-inline\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data: https:', 'ultraguard-security-suite' ),
                                          'rows' => 5,
                                          'default' => $s( 'csp_value', "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:;" ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                ],
            ] ],

            'form' => [
                'enable'  => true,
                'id'      => 'security-headers-form',
                'ajax'    => true,
                'action'  => 'ultraguard_headers_save',
                'nonce'   => $this->create_nonce( 'ultraguard_admin_nonce' ),
                'submit'  => [
                    'text'         => __( 'Save Security Header Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ],
        ], $context );
    }

    // ── Helpers ────────────────────────────────────────────────────────────────

    private function enabled_count(): int {
        $keys  = [ 'xframe_enabled', 'xcontent_type_enabled', 'xxss_enabled', 'referrer_policy_enabled', 'permissions_policy_enabled', 'hsts_enabled', 'csp_enabled', 'coop_enabled', 'coep_enabled' ];
        $count = 0;
        foreach ( $keys as $k ) {
            if ( $this->get_setting( 'headers_' . $k, $k !== 'hsts_enabled' && $k !== 'csp_enabled' && $k !== 'coop_enabled' && $k !== 'coep_enabled' ) ) {
                $count++;
            }
        }
        return $count;
    }

    private function enabled_count_badge(): string {
        $n = $this->enabled_count();
        /* translators: %d: number */
        return sprintf( _n( '%d Header Active', '%d Headers Active', $n, 'ultraguard-security-suite' ), $n );
    }
}
