<?php
/**
 * HtaccessSecurityRules — Security rules management subpage.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

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

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

class HtaccessSecurityRules extends BasePage {

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

    public function get_scheme( $context ): array {
        $nonce = $this->create_nonce( 'ultraguard_admin_nonce' );

        $features = [
            'disable_directory_listing' => [ 'label' => __( 'Disable Directory Listing',    'ultraguard-security-suite' ), 'icon' => 'dashicons-minus-alt',      'description' => __( 'Prevents browsers from listing directory contents when no index file exists.',                       'ultraguard-security-suite' ) ],
            'protect_wp_config'         => [ 'label' => __( 'Protect wp-config.php',         'ultraguard-security-suite' ), 'icon' => 'dashicons-lock',            'description' => __( 'Block direct web access to the WordPress config file (contains DB credentials).',                    'ultraguard-security-suite' ) ],
            'protect_wp_includes'       => [ 'label' => __( 'Protect wp-includes',            'ultraguard-security-suite' ), 'icon' => 'dashicons-shield',          'description' => __( 'Block PHP execution in the wp-includes directory.',                                                  'ultraguard-security-suite' ) ],
            'protect_uploads_php'       => [ 'label' => __( 'Block PHP in Uploads',           'ultraguard-security-suite' ), 'icon' => 'dashicons-upload',          'description' => __( 'Prevent malicious PHP files uploaded via vulnerabilities from executing.',                           'ultraguard-security-suite' ) ],
            'block_xmlrpc'              => [ 'label' => __( 'Block XML-RPC',                  'ultraguard-security-suite' ), 'icon' => 'dashicons-dismiss',         'description' => __( 'Deny access to xmlrpc.php — a common amplification vector for brute-force attacks.',              'ultraguard-security-suite' ) ],
            'security_headers'          => [ 'label' => __( 'Add Security Headers',           'ultraguard-security-suite' ), 'icon' => 'dashicons-admin-network',   'description' => __( 'X-Frame-Options, X-Content-Type-Options, XSS-Protection, Referrer-Policy, Permissions-Policy.',    'ultraguard-security-suite' ) ],
            'block_hotlinking'          => [ 'label' => __( 'Block Image Hotlinking',         'ultraguard-security-suite' ), 'icon' => 'dashicons-format-image',    'description' => __( 'Prevent other sites from embedding your images directly (bandwidth theft).',                        'ultraguard-security-suite' ) ],
            'block_author_scan'         => [ 'label' => __( 'Block User Enumeration',         'ultraguard-security-suite' ), 'icon' => 'dashicons-admin-users',     'description' => __( 'Block ?author=N requests that expose WordPress usernames to attackers.',                            'ultraguard-security-suite' ) ],
            'block_bad_bots'            => [ 'label' => __( 'Block Malicious Bots',           'ultraguard-security-suite' ), 'icon' => 'dashicons-robot',           'description' => __( 'Block known attack tools: sqlmap, nikto, masscan, libwww-perl and similar.',                        'ultraguard-security-suite' ) ],
            'prevent_script_injection'  => [ 'label' => __( 'Block Script Injection',         'ultraguard-security-suite' ), 'icon' => 'dashicons-editor-code',     'description' => __( 'Reject requests with injected HTML/script tags or GLOBALS/_REQUEST manipulations in the URL.',     'ultraguard-security-suite' ) ],
            'limit_file_access'         => [ 'label' => __( 'Hide Sensitive Files',           'ultraguard-security-suite' ), 'icon' => 'dashicons-hidden',          'description' => __( 'Block direct access to readme.html, license.txt, wp-activate.php.',                                'ultraguard-security-suite' ) ],
        ];

        $enabled_count = 0;
        $feature_items = [];
        foreach ( $features as $key => $info ) {
            $on = (bool) get_option( 'ultraguard_htaccess_feature_' . $key, false );
            if ( $on ) { $enabled_count++; }
            $feature_items[] = [
                'icon'    => $info['icon'],
                'text'    => $info['label'],
                'description' => $info['description'],
                'badge'   => [ 'text' => $on ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ), 'badge_type' => $on ? 'success' : 'secondary' ],
                'actions' => [
                    $this->create_ajax_button(
                        $on ? __( 'Disable', 'ultraguard-security-suite' ) : __( 'Enable', 'ultraguard-security-suite' ),
                        'ultraguard_toggle_security_feature',
                        [ 'feature' => $key, 'enabled' => ! $on ],
                        $on ? 'secondary' : 'primary',
                        $on ? 'dashicons-no-alt' : 'dashicons-yes'
                    ),
                ],
            ];
        }

        $cloud_rules = array_values( array_filter( (array) get_option( 'ultraguard_cloud_htaccess_rules', [] ), 'is_array' ) );
        $cloud_items = array_map(
            function( array $rule ): array {
                return [
                    'icon'        => 'dashicons-cloud',
                    'text'        => sanitize_text_field( (string) ( $rule['title'] ?? __( 'Cloud rule', 'ultraguard-security-suite' ) ) ),
                    'description' => wp_kses_post( (string) ( $rule['description'] ?? '' ) ),
                    'badge'       => [
                        'text'       => __( 'Remote Update', 'ultraguard-security-suite' ),
                        'badge_type' => 'info',
                    ],
                    'actions'     => [
                        $this->create_ajax_button(
                            __( 'Insert In Custom Rules', 'ultraguard-security-suite' ),
                            'ultraguard_insert_template',
                            [ 'template' => sanitize_key( (string) ( $rule['id'] ?? '' ) ) ],
                            'secondary',
                            'dashicons-plus'
                        ),
                    ],
                ];
            },
            $cloud_rules
        );

        return apply_filters( 'ultraguard_htaccess_security_rules_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-htaccess-security-rules',
            'page_slug' => 'htaccess-security-rules',
            'class'     => 'ultraguard-htaccess-security-rules-page',

            'header' => [
                'title'    => __( 'Security Rules', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Toggle built-in .htaccess security rules and apply them to your file', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %1$d: integer, %2$d: integer */
                    'text'       => sprintf( __( '%1$d / %2$d Enabled', 'ultraguard-security-suite' ), $enabled_count, count( $features ) ),
                    'badge_type' => $enabled_count === count( $features ) ? 'success' : ( $enabled_count > 0 ? 'warning' : 'secondary' ),
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Enable All',   'ultraguard-security-suite' ), 'ultraguard_enable_all_security',  [], 'primary',   'dashicons-yes',    __( 'Enable all security features?',  'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Disable All',  'ultraguard-security-suite' ), 'ultraguard_disable_all_security', [], 'secondary', 'dashicons-no',     __( 'Disable all security features?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Apply Rules',  'ultraguard-security-suite' ), 'ultraguard_apply_htaccess_rules', [], 'secondary', 'dashicons-update', __( 'Write enabled rules to .htaccess?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Test Rules',   'ultraguard-security-suite' ), 'ultraguard_test_htaccess_rules',  [], 'secondary', 'dashicons-yes'    ),
                ],
            ],

            'data' => [
                // Stats
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Features',   'ultraguard-security-suite' ), 'value' => count( $features ), 'format' => 'number', 'icon' => 'dashicons-shield',    'class' => 'info'    ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Features Enabled', 'ultraguard-security-suite' ), 'value' => $enabled_count,    'format' => 'number', 'icon' => 'dashicons-yes-alt',   'class' => 'success' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Features Disabled','ultraguard-security-suite' ), 'value' => count( $features ) - $enabled_count, 'format' => 'number', 'icon' => 'dashicons-no-alt', 'class' => 'secondary' ] ],
                    ],
                ],

                // Feature toggles list
                [
                    'type'    => 'card',
                    'title'   => __( 'Security Features', 'ultraguard-security-suite' ),
                    'icon'    => 'dashicons-shield-alt',
                    'data'    => [ [ 'type' => 'list', 'list_type' => 'ul', 'items' => $feature_items ] ],
                    'footer'  => [
                        'type'      => 'button-group',
                        'alignment' => 'right',
                        'buttons'   => [
                            $this->create_ajax_button( __( 'Backup Before Apply', 'ultraguard-security-suite' ), 'ultraguard_backup_security_rules', [], 'secondary', 'dashicons-backup' ),
                            $this->create_ajax_button( __( 'Apply to .htaccess',  'ultraguard-security-suite' ), 'ultraguard_apply_htaccess_rules',  [], 'primary',   'dashicons-update', __( 'Write the enabled rules to your .htaccess file?', 'ultraguard-security-suite' ) ),
                        ],
                    ],
                ],

                // Export / Generate
                [
                    'type'    => 'card',
                    'title'   => __( 'Export / Generate Rules', 'ultraguard-security-suite' ),
                    'icon'    => 'dashicons-code-standards',
                    'data'    => [ [ 'type' => 'paragraph', 'content' => __( 'Generate rule snippets from your current feature selection, or export the active security section of your .htaccess file.', 'ultraguard-security-suite' ) ] ],
                    'footer'  => [
                        'type'      => 'button-group',
                        'alignment' => 'center',
                        'buttons'   => [
                            $this->create_ajax_button( __( 'Generate Rules',       'ultraguard-security-suite' ), 'ultraguard_generate_htaccess_rules', [], 'secondary', 'dashicons-code-standards' ),
                            $this->create_ajax_button( __( 'Export Security Rules','ultraguard-security-suite' ), 'ultraguard_export_security_rules',   [], 'secondary', 'dashicons-download'       ),
                            $this->create_ajax_button( __( 'Copy to Clipboard',   'ultraguard-security-suite' ), 'ultraguard_copy_security_rules',     [], 'secondary', 'dashicons-clipboard'      ),
                        ],
                    ],
                ],
                [
                    'type'    => 'card',
                    'title'   => __( 'Cloud Rule Templates', 'ultraguard-security-suite' ),
                    'icon'    => 'dashicons-cloud',
                    'data'    => ! empty( $cloud_items )
                        ? [ [ 'type' => 'list', 'list_type' => 'ul', 'items' => $cloud_items ] ]
                        : [ [ 'type' => 'paragraph', 'content' => __( 'No cloud .htaccess rule updates have been synced yet.', 'ultraguard-security-suite' ) ] ],
                ],
            ],

            'form' => [ 'enable' => false ],
        ], $context );
    }
}
