<?php
/**
 * HardeningPage — WordPress Hardening admin page.
 *
 * Tabs:
 *   Overview       — hardening score stats + live audit checklist
 *   Core Security  — XML-RPC, REST API, WP version, RSD, embeds, pingbacks
 *   Auth & Files   — file-edit constants, HTTPS admin, user enumeration, app passwords
 *   wp-config      — live status of wp-config.php security constants
 *
 * @package UltraguardPro\modules\hardening\pages
 */

namespace UltraguardPro\modules\hardening\pages;

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

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

class HardeningPage 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 = false ) => $this->get_setting( 'hardening_' . $k, $d );

        $checks      = $this->run_checks();
        $score       = $this->score( $checks );
        $grade       = $this->grade( $score );
        $pass        = count( array_filter( $checks, fn( $c ) => $c['pass'] ) );
        $fail        = count( $checks ) - $pass;
        $score_class = $score >= 80 ? 'success' : ( $score >= 50 ? 'warning' : 'danger' );

        return apply_filters( 'ultraguard_hardening_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-hardening',
            'page_slug' => 'hardening',
            'class'     => 'ultraguard-hardening-page',

            'header' => [
                'title'    => __( 'WordPress Hardening', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Apply security best-practices to lock down your WordPress installation.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %1$d: integer, %2$s: string */
                    'text'       => sprintf( __( 'Score: %1$d/100 (Grade %2$s)', 'ultraguard-security-suite' ), $score, $grade ),
                    'badge_type' => $score_class,
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Run Audit',    'ultraguard-security-suite' ), 'ultraguard_hardening_run_check', [], 'secondary', 'dashicons-search'  ),
                    $this->create_ajax_button( __( 'Harden All',   'ultraguard-security-suite' ), 'ultraguard_hardening_apply_all', [], 'primary',   'dashicons-shield',
                        __( 'Enable all hardening settings? This will apply changes to your site immediately.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [ [
                'type' => 'tabs',
                'id'   => 'hardening-settings-tabs',
                'tabs' => [

                    // ── Tab 1: Overview ──────────────────────────────────
                    [
                        'id'    => 'overview',
                        'title' => __( 'Overview', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-chart-pie',
                        'data'  => [
                            [
                                'type'    => 'grid',
                                'columns' => 12,
                                'gap'     => '16px',
                                'items'   => [
                                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Hardening Score', 'ultraguard-security-suite' ), 'value' => $score . '/100',  'icon' => 'dashicons-chart-pie', 'class' => $score_class ] ],
                                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Security Grade',  'ultraguard-security-suite' ), 'value' => 'Grade ' . $grade, 'icon' => 'dashicons-awards',    'class' => $score_class ] ],
                                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Checks Passing', 'ultraguard-security-suite' ),  'value' => $pass,              'icon' => 'dashicons-yes-alt',   'class' => 'success'    ] ],
                                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Issues Found',   'ultraguard-security-suite' ),  'value' => $fail,              'icon' => 'dashicons-warning',   'class' => $fail > 0 ? 'danger' : 'success' ] ],
                                ],
                            ],
                            [
                                'type'  => 'card',
                                'title' => __( 'Live Hardening Audit', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-shield-alt',
                                'data'  => [ [
                                    'type'  => 'list',
                                    'items' => $this->checks_to_list_items( $checks ),
                                ] ],
                            ],
                        ],
                    ],

                    // ── Tab 2: Core Security ─────────────────────────────
                    [
                        'id'    => 'core-security',
                        'title' => __( 'Core Security', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-shield',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Core Security', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-shield',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'hardening_disable_xmlrpc',
                                          'label' => __( 'Disable XML-RPC', 'ultraguard-security-suite' ),
                                          'description' => __( 'Block xmlrpc.php entirely (uses PHP filter, works alongside .htaccess rule).', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disable_xmlrpc' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_disable_rest_unauthenticated',
                                          'label' => __( 'Require Auth for REST API', 'ultraguard-security-suite' ),
                                          'description' => __( 'Return 401 for all REST API requests from unauthenticated users.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disable_rest_unauthenticated' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_remove_wp_version',
                                          'label' => __( 'Hide WordPress Version', 'ultraguard-security-suite' ),
                                          'description' => __( 'Remove the generator meta tag from &lt;head&gt;, RSS feeds, and HTTP headers.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'remove_wp_version' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_remove_rsd_link',
                                          'label' => __( 'Remove RSD / WLW Links', 'ultraguard-security-suite' ),
                                          'description' => __( 'Remove Really Simple Discovery and Windows Live Writer meta tags from &lt;head&gt;.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'remove_rsd_link' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_disable_embeds',
                                          'label' => __( 'Disable oEmbed / wp-embed.js', 'ultraguard-security-suite' ),
                                          'description' => __( 'Remove the wp-embed.js script from the footer (speeds up pages that don\'t use embeds).', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disable_embeds' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_disable_pingbacks',
                                          'label' => __( 'Disable Pingbacks & Trackbacks', 'ultraguard-security-suite' ),
                                          'description' => __( 'Remove the pingback.ping XML-RPC method and hide the pingback URL in &lt;head&gt;.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disable_pingbacks' ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 3: Auth & Files ──────────────────────────────
                    [
                        'id'    => 'auth-files',
                        'title' => __( 'Auth & Files', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-lock',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Auth & File Security', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-lock',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'hardening_disallow_file_edit',
                                          'label' => __( 'Disable File Editing (DISALLOW_FILE_EDIT)', 'ultraguard-security-suite' ),
                                          'description' => __( 'Sets DISALLOW_FILE_EDIT=true in wp-config to prevent plugin/theme editing from wp-admin.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disallow_file_edit', defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_disallow_file_mods',
                                          'label' => __( 'Disable All File Mods (DISALLOW_FILE_MODS)', 'ultraguard-security-suite' ),
                                          'description' => __( 'Prevents plugin/theme installation and updates from the admin. Use on locked-down production sites.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disallow_file_mods', defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_force_ssl_admin',
                                          'label' => __( 'Force HTTPS for Admin (FORCE_SSL_ADMIN)', 'ultraguard-security-suite' ),
                                          'description' => __( 'Forces WordPress login and admin to use HTTPS.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'force_ssl_admin', defined( 'FORCE_SSL_ADMIN' ) && FORCE_SSL_ADMIN ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_disable_user_enumeration',
                                          'label' => __( 'Block User Enumeration', 'ultraguard-security-suite' ),
                                          'description' => __( 'Redirect /?author=N requests back to the homepage to prevent username discovery.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disable_user_enumeration' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_hide_login_errors',
                                          'label' => __( 'Hide Login Error Details', 'ultraguard-security-suite' ),
                                          'description' => __( 'Replace specific "wrong username/password" messages with a generic error.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'hide_login_errors' ) ],
                                        [ 'type' => 'toggle', 'name' => 'hardening_disable_application_passwords',
                                          'label' => __( 'Disable Application Passwords', 'ultraguard-security-suite' ),
                                          'description' => __( 'Disable Application Passwords (introduced in WP 5.6) if you don\'t use REST API clients.', 'ultraguard-security-suite' ),
                                          'default' => $s( 'disable_application_passwords' ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 4: wp-config ─────────────────────────────────
                    [
                        'id'    => 'wp-config',
                        'title' => __( 'wp-config', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-editor-code',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'wp-config.php Constants — Current Status', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-editor-code',
                                    'data'  => [ [
                                        'type'  => 'list',
                                        'items' => $this->wp_config_status_items(),
                                    ] ],
                                ] ],
                            ],
                        ] ],
                    ],

                ],
            ] ],

            'form' => [
                'enable'  => true,
                'id'      => 'hardening-settings-form',
                'ajax'    => true,
                'action'  => 'ultraguard_hardening_save',
                'nonce'   => $this->create_nonce( 'ultraguard_admin_nonce' ),
                'submit'  => [
                    'text'         => __( 'Save & Apply Hardening Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ],
        ], $context );
    }

    // =========================================================================
    // PRIVATE HELPERS
    // =========================================================================

    private function run_checks(): array {
        return [
            'xmlrpc' => [
                'label'    => __( 'XML-RPC', 'ultraguard-security-suite' ),
                'pass'     => ! apply_filters( 'xmlrpc_enabled', true ),
                'severity' => 'high',
                'fix_key'  => 'disable_xmlrpc',
                'detail'   => __( 'XML-RPC should be disabled unless required for mobile apps or Jetpack.', 'ultraguard-security-suite' ),
            ],
            'file_edit' => [
                'label'    => __( 'DISALLOW_FILE_EDIT', 'ultraguard-security-suite' ),
                'pass'     => defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT,
                'severity' => 'high',
                'fix_key'  => 'disallow_file_edit',
                'detail'   => __( 'Admin file editor is a common attack vector on compromised admin accounts.', 'ultraguard-security-suite' ),
            ],
            'debug_off' => [
                'label'    => __( 'WP_DEBUG is off', 'ultraguard-security-suite' ),
                'pass'     => ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ),
                'severity' => 'high',
                'detail'   => __( 'Debug mode exposes stack traces and configuration details to the public.', 'ultraguard-security-suite' ),
            ],
            'ssl' => [
                'label'    => __( 'SSL / HTTPS active', 'ultraguard-security-suite' ),
                'pass'     => is_ssl() || ( defined( 'FORCE_SSL_ADMIN' ) && FORCE_SSL_ADMIN ),
                'severity' => 'critical',
                'fix_key'  => 'force_ssl_admin',
                'detail'   => __( 'All traffic (especially admin) must use HTTPS.', 'ultraguard-security-suite' ),
            ],
            'admin_user' => [
                'label'    => __( 'No "admin" username', 'ultraguard-security-suite' ),
                'pass'     => get_user_by( 'login', 'admin' ) === false,
                'severity' => 'critical',
                'detail'   => __( 'The "admin" username is the first target in brute-force attacks.', 'ultraguard-security-suite' ),
            ],
            'wp_version' => [
                'label'    => __( 'WordPress version hidden', 'ultraguard-security-suite' ),
                'pass'     => ! has_action( 'wp_head', 'wp_generator' ),
                'severity' => 'medium',
                'fix_key'  => 'remove_wp_version',
                'detail'   => __( 'Exposing the WP version helps attackers target known vulnerabilities.', 'ultraguard-security-suite' ),
            ],
            'rsd_link' => [
                'label'    => __( 'RSD / WLW meta removed', 'ultraguard-security-suite' ),
                'pass'     => ! has_action( 'wp_head', 'rsd_link' ),
                'severity' => 'low',
                'fix_key'  => 'remove_rsd_link',
                'detail'   => __( 'Legacy discovery meta tags expose service endpoints unnecessarily.', 'ultraguard-security-suite' ),
            ],
            'config_perms' => [
                'label'    => __( 'wp-config.php permissions ≤ 640', 'ultraguard-security-suite' ),
                'pass'     => $this->check_config_perms(),
                'severity' => 'high',
                'detail'   => __( 'World-readable wp-config.php exposes database credentials on shared hosts.', 'ultraguard-security-suite' ),
            ],
        ];
    }

    private function check_config_perms(): bool {
        $path = ABSPATH . 'wp-config.php';
        if ( ! file_exists( $path ) ) { return true; }
        $perms = substr( sprintf( '%o', fileperms( $path ) ), -3 );
        return (int) $perms[2] === 0;
    }

    private function score( array $checks ): int {
        $weights = [ 'critical' => 25, 'high' => 15, 'medium' => 8, 'low' => 4 ];
        $total = $earned = 0;
        foreach ( $checks as $c ) {
            $w = $weights[ $c['severity'] ?? 'low' ] ?? 4;
            $total += $w;
            if ( $c['pass'] ) { $earned += $w; }
        }
        return $total > 0 ? (int) round( ( $earned / $total ) * 100 ) : 0;
    }

    private function grade( int $score ): string {
        if ( $score >= 90 ) { return 'A'; }
        if ( $score >= 75 ) { return 'B'; }
        if ( $score >= 60 ) { return 'C'; }
        if ( $score >= 40 ) { return 'D'; }
        return 'F';
    }

    private function checks_to_list_items( array $checks ): array {
        $severity_badge = [ 'critical' => 'danger', 'high' => 'warning', 'medium' => 'info', 'low' => 'secondary' ];
        $items = [];
        foreach ( $checks as $c ) {
            $items[] = [
                'icon'        => $c['pass'] ? 'dashicons-yes-alt' : 'dashicons-warning',
                'text'        => $c['label'],
                'class'       => $c['pass'] ? 'ug-check-pass' : 'ug-check-fail',
                'badge'       => $c['pass']
                    ? [ 'text' => __( 'Pass', 'ultraguard-security-suite' ), 'badge_type' => 'success' ]
                    : [ 'text' => ucfirst( $c['severity'] ?? 'low' ), 'badge_type' => $severity_badge[ $c['severity'] ?? 'low' ] ],
                'description' => $c['pass'] ? '' : $c['detail'],
            ];
        }
        return $items;
    }

    private function wp_config_status_items(): array {
        $constants = [
            'DISALLOW_FILE_EDIT'  => [ 'desc' => __( 'Prevent plugin/theme editing from admin.', 'ultraguard-security-suite' ),        'recommended' => true  ],
            'DISALLOW_FILE_MODS'  => [ 'desc' => __( 'Prevent all file modifications including updates.', 'ultraguard-security-suite' ), 'recommended' => false ],
            'FORCE_SSL_ADMIN'     => [ 'desc' => __( 'Force HTTPS for admin area and login.', 'ultraguard-security-suite' ),             'recommended' => true  ],
            'WP_DEBUG'            => [ 'desc' => __( 'Enable debug mode (should be FALSE in production).', 'ultraguard-security-suite' ),'recommended' => false ],
            'WP_AUTO_UPDATE_CORE' => [ 'desc' => __( 'Auto-update WordPress core.', 'ultraguard-security-suite' ),                       'recommended' => true  ],
        ];
        $items = [];
        foreach ( $constants as $const => $info ) {
            $defined = defined( $const );
            $value   = $defined ? constant( $const ) : null;
            $pass    = $info['recommended'] ? ( $defined && $value ) : ( ! $defined || ! $value );
            $items[] = [
                'icon'        => 'dashicons-editor-code',
                'text'        => $const,
                'description' => $info['desc'],
                'badge'       => [
                    'text'       => $defined ? ( $value ? 'true' : 'false' ) : __( 'not set', 'ultraguard-security-suite' ),
                    'badge_type' => $pass ? 'success' : 'warning',
                ],
            ];
        }
        return $items;
    }
}
