<?php
/**
 * HtaccessPage — Full admin page for the .htaccess Manager module.
 *
 * Sections: Status cards, Code editor, Security presets, Backup history, Settings.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

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

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

class HtaccessPage extends BasePage {

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

    public function get_scheme( $context ): array {

        $htaccess_path = ABSPATH . '.htaccess';
        $file_exists   = file_exists( $htaccess_path );
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- direct writability check for page status only.
        $file_writable = $file_exists && is_writable( $htaccess_path );
        $file_size     = $file_exists ? filesize( $htaccess_path ) : 0;
        $file_modified = $file_exists ? filemtime( $htaccess_path ) : 0;

        return apply_filters( 'ultraguard_htaccess_page_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-htaccess',
            'page_slug' => 'htaccess',
            'class'     => 'ultraguard-htaccess-page',
            'header'    => [
                'id'       => 'htaccess-header',
                'title'    => __( '.htaccess Manager', 'ultraguard-security-suite' ),
                'subtitle' => __( 'View, edit and harden your WordPress .htaccess file with automatic backup', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_ajax_button(
                        __( 'Save .htaccess', 'ultraguard-security-suite' ),
                        'ultraguard_htaccess_save',
                        [],
                        'primary',
                        'dashicons-saved',
                        __( 'Save changes to .htaccess? A backup will be created first.', 'ultraguard-security-suite' )
                    ),
                    $this->create_ajax_button(
                        __( 'Refresh', 'ultraguard-security-suite' ),
                        'ultraguard_htaccess_read',
                        [],
                        'secondary',
                        'dashicons-update'
                    ),
                    $this->create_ajax_button(
                        __( 'Backup Now', 'ultraguard-security-suite' ),
                        'ultraguard_create_htaccess_backup',
                        [],
                        'secondary',
                        'dashicons-backup'
                    ),
                ],
            ],
            'data' => [
                $this->status_row( $file_exists, $file_writable, $file_size, $file_modified ),
                [
                    'type' => 'tabs',
                    'id'   => 'htaccess-tabs',
                    'tabs' => [
                        [
                            'id'       => 'editor',
                            'label'    => __( 'Editor', 'ultraguard-security-suite' ),
                            'icon'     => 'dashicons-edit',
                            'children' => [ $this->editor_content() ],
                        ],
                        [
                            'id'       => 'presets',
                            'label'    => __( 'Security Presets', 'ultraguard-security-suite' ),
                            'icon'     => 'dashicons-shield-alt',
                            'children' => [ $this->presets_content() ],
                        ],
                        [
                            'id'       => 'backups',
                            'label'    => __( 'Backups', 'ultraguard-security-suite' ),
                            'icon'     => 'dashicons-backup',
                            'children' => [ $this->backups_content() ],
                        ],
                        [
                            'id'       => 'settings',
                            'label'    => __( 'Settings', 'ultraguard-security-suite' ),
                            'icon'     => 'dashicons-admin-settings',
                            'children' => [ $this->settings_content() ],
                        ],
                    ],
                ],
            ],
            'form' => [ 'enable' => false ],
        ], $context );
    }

    // ── Status row ────────────────────────────────────────────────────────────

    private function status_row( bool $exists, bool $writable, int $size, int $modified ): array {
        return [
            'type'       => 'grid',
            'columns'    => 12,
            'gap'        => '16px',
            'responsive' => true,
            'items'      => [
                [
                    'span'       => 3,
                    'responsive' => [ 'sm' => 12, 'md' => 6, 'lg' => 3 ],
                    'component'  => [
                        'type'   => 'stat-card',
                        'title'  => __( 'File Exists', 'ultraguard-security-suite' ),
                        'value'  => $exists ? __( 'Yes', 'ultraguard-security-suite' ) : __( 'No', 'ultraguard-security-suite' ),
                        'format' => 'string',
                        'icon'   => 'dashicons-media-text',
                        'class'  => $exists ? 'success' : 'danger',
                    ],
                ],
                [
                    'span'       => 3,
                    'responsive' => [ 'sm' => 12, 'md' => 6, 'lg' => 3 ],
                    'component'  => [
                        'type'   => 'stat-card',
                        'title'  => __( 'Writable', 'ultraguard-security-suite' ),
                        'value'  => $writable ? __( 'Yes', 'ultraguard-security-suite' ) : __( 'No', 'ultraguard-security-suite' ),
                        'format' => 'string',
                        'icon'   => 'dashicons-edit',
                        'class'  => $writable ? 'success' : 'warning',
                    ],
                ],
                [
                    'span'       => 3,
                    'responsive' => [ 'sm' => 12, 'md' => 6, 'lg' => 3 ],
                    'component'  => [
                        'type'   => 'stat-card',
                        'title'  => __( 'File Size', 'ultraguard-security-suite' ),
                        'value'  => $size ? $this->format_file_size( $size ) : '—',
                        'format' => 'string',
                        'icon'   => 'dashicons-database',
                        'class'  => 'info',
                    ],
                ],
                [
                    'span'       => 3,
                    'responsive' => [ 'sm' => 12, 'md' => 6, 'lg' => 3 ],
                    'component'  => [
                        'type'   => 'stat-card',
                        'title'  => __( 'Last Modified', 'ultraguard-security-suite' ),
                        'value'  => $modified ? $this->format_time_ago( $modified ) : __( 'Unknown', 'ultraguard-security-suite' ),
                        'format' => 'string',
                        'icon'   => 'dashicons-clock',
                        'class'  => 'info',
                    ],
                ],
            ],
        ];
    }

    // ── Editor ────────────────────────────────────────────────────────────────

    private function editor_content(): array {
        $htaccess_path = ABSPATH . '.htaccess';
        $content       = file_exists( $htaccess_path ) ? file_get_contents( $htaccess_path ) : '';

        return [
            'type'    => 'grid',
            'columns' => 1,
            'gap'     => '20px',
            'items'   => [
                [
                    'component' => [
                        'type'  => 'alert-box',
                        'alert_type' => 'warning',
                        'icon'  => 'dashicons-warning',
                        'message' => __( 'Editing .htaccess incorrectly can break your site. A backup is created automatically before saving.', 'ultraguard-security-suite' ),
                    ],
                ],
                [
                    'component' => [
                        'type'  => 'card',
                        'title' => __( '.htaccess Content', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-edit',
                        'data'  => [
                            [
                                'type'     => 'code-editor',
                                'name'     => 'htaccess_content',
                                'language' => 'apache',
                                'height'   => '500px',
                                'default'  => $content,
                            ],
                        ],
                        'footer' => [
                            'type'      => 'button-group',
                            'alignment' => 'right',
                            'buttons'   => [
                                $this->create_ajax_button(
                                    __( 'Validate Syntax', 'ultraguard-security-suite' ),
                                    'ultraguard_validate_htaccess_syntax',
                                    [],
                                    'secondary',
                                    'dashicons-yes-alt'
                                ),
                                $this->create_ajax_button(
                                    __( 'Save .htaccess', 'ultraguard-security-suite' ),
                                    'ultraguard_htaccess_save',
                                    [],
                                    'primary',
                                    'dashicons-saved',
                                    __( 'Save changes to .htaccess?', 'ultraguard-security-suite' )
                                ),
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }

    // ── Security Presets ──────────────────────────────────────────────────────

    private function presets_content(): array {
        $presets = [
            [
                'key'         => 'protect_wp_includes',
                'title'       => __( 'Protect wp-includes', 'ultraguard-security-suite' ),
                'description' => __( 'Blocks direct access to PHP files in the wp-includes directory.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-shield',
                'risk'        => 'low',
            ],
            [
                'key'         => 'disable_directory_listing',
                'title'       => __( 'Disable Directory Listing', 'ultraguard-security-suite' ),
                'description' => __( 'Prevents Apache from listing directory contents when no index file exists.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-media-archive',
                'risk'        => 'low',
            ],
            [
                'key'         => 'protect_wp_config',
                'title'       => __( 'Protect wp-config.php', 'ultraguard-security-suite' ),
                'description' => __( 'Blocks all external access to wp-config.php.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-lock',
                'risk'        => 'low',
            ],
            [
                'key'         => 'block_xmlrpc',
                'title'       => __( 'Block XML-RPC', 'ultraguard-security-suite' ),
                'description' => __( 'Disables XML-RPC endpoint to prevent brute-force and DDoS amplification attacks.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-no',
                'risk'        => 'medium',
            ],
            [
                'key'         => 'security_headers',
                'title'       => __( 'Add Security Headers', 'ultraguard-security-suite' ),
                'description' => __( 'Adds X-Frame-Options, X-XSS-Protection, X-Content-Type-Options headers.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-admin-network',
                'risk'        => 'low',
            ],
            [
                'key'         => 'block_hotlinking',
                'title'       => __( 'Block Image Hotlinking', 'ultraguard-security-suite' ),
                'description' => __( 'Prevents other sites from directly linking to your images.', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-format-image',
                'risk'        => 'low',
            ],
        ];

        $preset_cards = [];
        foreach ( $presets as $preset ) {
            $risk_badge_type = match ( $preset['risk'] ) { 'high' => 'danger', 'medium' => 'warning', default => 'success' };
            $preset_cards[] = [
                'type'  => 'card',
                'title' => $preset['title'],
                'icon'  => $preset['icon'],
                'badge' => [
                    'text'       => ucfirst( $preset['risk'] ) . ' ' . __( 'risk', 'ultraguard-security-suite' ),
                    'badge_type' => $risk_badge_type,
                ],
                'data'  => [
                    [
                        'type'    => 'paragraph',
                        'text'    => $preset['description'],
                    ],
                ],
                'footer' => [
                    'type'      => 'button-group',
                    'alignment' => 'left',
                    'buttons'   => [
                        $this->create_ajax_button(
                            __( 'Apply Preset', 'ultraguard-security-suite' ),
                            'ultraguard_insert_template',
                            [ 'preset' => $preset['key'] ],
                            'secondary',
                            'dashicons-plus-alt',
                            /* translators: %s: string */
                            sprintf( __( 'Apply the "%s" preset to your .htaccess?', 'ultraguard-security-suite' ), $preset['title'] )
                        ),
                    ],
                ],
            ];
        }

        return [
            'type'    => 'grid',
            'columns' => 1,
            'gap'     => '20px',
            'items'   => [
                [
                    'component' => [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'icon'       => 'dashicons-info',
                        'message'    => __( 'Apply pre-built security rules to your .htaccess. Each preset appends a clearly marked block so you can easily review or remove it.', 'ultraguard-security-suite' ),
                    ],
                ],
                [
                    'component' => [
                        'type'    => 'card-grid',
                        'columns' => 2,
                        'title'   => __( 'Available Presets', 'ultraguard-security-suite' ),
                        'cards'   => array_map( function( $c ) {
                            // card-grid expects simple cards; wrap content appropriately
                            return [
                                'icon'    => $c['icon'],
                                'title'   => $c['title'],
                                'content' => isset( $c['data'][0]['text'] ) ? $c['data'][0]['text'] : '',
                                'footer'  => $c['title'], // placeholder text for card-grid footer
                            ];
                        }, $preset_cards ),
                    ],
                ],
                // Full interactive preset cards rendered as a grid of proper card widgets
                [
                    'component' => [
                        'type'    => 'grid',
                        'columns' => 2,
                        'gap'     => '16px',
                        'items'   => array_map( fn( $c ) => [ 'component' => $c ], $preset_cards ),
                    ],
                ],
            ],
        ];
    }

    // ── Backups ───────────────────────────────────────────────────────────────

    private function backups_content(): array {
        $backup_dir  = WP_CONTENT_DIR . '/uploads/ultraguard-backups/';
        $backups     = [];

        if ( is_dir( $backup_dir ) ) {
            $files = glob( $backup_dir . 'htaccess-backup-*.txt' );
            if ( $files ) {
                rsort( $files );
                foreach ( array_slice( $files, 0, 30 ) as $file ) {
                    $backups[] = [
                        'file_name'  => [ 'content' => esc_html( basename( $file ) ), 'class' => '' ],
                        'file_size'  => $this->format_file_size( filesize( $file ) ),
                        'created_at' => esc_html( $this->format_time_ago( filemtime( $file ) ) ),
                        'data-file'  => esc_attr( basename( $file ) ),
                    ];
                }
            }
        }

        return [
            'type'    => 'grid',
            'columns' => 1,
            'gap'     => '20px',
            'items'   => [
                [
                    'component' => [
                        'type'  => 'card',
                        'title' => __( 'Backup History', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-backup',
                        'actions' => [
                            $this->create_ajax_button(
                                __( 'Create Backup', 'ultraguard-security-suite' ),
                                'ultraguard_create_htaccess_backup',
                                [],
                                'primary',
                                'dashicons-plus-alt'
                            ),
                        ],
                        'data'  => [
                            empty( $backups )
                                ? [
                                    'type'       => 'alert-box',
                                    'alert_type' => 'info',
                                    'icon'       => 'dashicons-info',
                                    'message'    => __( 'No backups found. Backups are created automatically when you save changes.', 'ultraguard-security-suite' ),
                                ]
                                : [
                                    'type'    => 'data-table',
                                    'id'      => 'htaccess-backups-table',
                                    'columns' => [
                                        'file_name'  => [ 'title' => __( 'Backup File', 'ultraguard-security-suite' ) ],
                                        'file_size'  => [ 'title' => __( 'Size',        'ultraguard-security-suite' ) ],
                                        'created_at' => [ 'title' => __( 'Created',     'ultraguard-security-suite' ), 'sortable' => true ],
                                    ],
                                    'data'        => $backups,
                                    'pagination'  => [ 'enabled' => true, 'page_size' => 10 ],
                                    'empty_state' => [ 'title' => __( 'No backups found', 'ultraguard-security-suite' ) ],
                                ],
                        ],
                    ],
                ],
            ],
        ];
    }

    // ── Settings ──────────────────────────────────────────────────────────────

    private function settings_content(): array {
        return [
            'type'       => 'grid',
            'columns'    => 12,
            'gap'        => '20px',
            'responsive' => true,
            'items'      => [
                [
                    'span'       => 6,
                    'responsive' => [ 'md' => 12, 'lg' => 6 ],
                    'component'  => [
                        'type'  => 'card',
                        'title' => __( 'Backup Settings', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-backup',
                        'data'  => [
                            [ 'type' => 'toggle', 'name' => 'htaccess_auto_backup',      'label' => __( 'Auto-Backup Before Save', 'ultraguard-security-suite' ), 'description' => __( 'Create a backup automatically before each save', 'ultraguard-security-suite' ), 'default' => true ],
                            [ 'type' => 'number', 'name' => 'htaccess_backup_keep',      'label' => __( 'Backups to Keep',         'ultraguard-security-suite' ), 'description' => __( 'Number of backup copies to retain',             'ultraguard-security-suite' ), 'min' => 1, 'max' => 100, 'default' => 10 ],
                            [ 'type' => 'toggle', 'name' => 'htaccess_backup_on_change', 'label' => __( 'Backup on External Change','ultraguard-security-suite' ), 'description' => __( 'Detect and backup when another plugin modifies the file', 'ultraguard-security-suite' ), 'default' => false ],
                        ],
                    ],
                ],
                [
                    'span'       => 6,
                    'responsive' => [ 'md' => 12, 'lg' => 6 ],
                    'component'  => [
                        'type'  => 'card',
                        'title' => __( 'Editor Settings', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-edit',
                        'data'  => [
                            [ 'type' => 'toggle', 'name' => 'htaccess_syntax_highlight', 'label' => __( 'Syntax Highlighting',  'ultraguard-security-suite' ), 'default' => true  ],
                            [ 'type' => 'toggle', 'name' => 'htaccess_line_numbers',     'label' => __( 'Show Line Numbers',   'ultraguard-security-suite' ), 'default' => true  ],
                            [ 'type' => 'toggle', 'name' => 'htaccess_validate_on_save', 'label' => __( 'Validate on Save',    'ultraguard-security-suite' ), 'description' => __( 'Run basic syntax checks before saving', 'ultraguard-security-suite' ), 'default' => true  ],
                            [ 'type' => 'toggle', 'name' => 'htaccess_track_changes',    'label' => __( 'Track Changes',       'ultraguard-security-suite' ), 'description' => __( 'Log who changed the file and when', 'ultraguard-security-suite' ),         'default' => true  ],
                        ],
                        'footer' => [
                            'type'      => 'button-group',
                            'alignment' => 'right',
                            'buttons'   => [
                                $this->create_ajax_button(
                                    __( 'Save Settings', 'ultraguard-security-suite' ),
                                    'ultraguard_save_htaccess_settings',
                                    [],
                                    'primary',
                                    'dashicons-saved'
                                ),
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }
}
