<?php
/**
 * HtaccessCustomRules — Custom rules editor subpage.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

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

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

class HtaccessCustomRules extends BasePage {

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

    private function import_rules_modal(): array {
        return [
            'id'      => 'htaccess-import-rules-modal',
            'title'   => __( 'Import .htaccess Rules', 'ultraguard-security-suite' ),
            'size'    => 'large',
            'content' => $this->modal_content( [
                [
                    'type'        => 'textarea',
                    'name'        => 'htaccess_content',
                    'label'       => __( '.htaccess Content', 'ultraguard-security-suite' ),
                    'rows'        => 16,
                    'placeholder' => "# Paste the .htaccess content you want to import here\n<IfModule mod_rewrite.c>\nRewriteEngine On\n</IfModule>",
                    'description' => __( 'Paste the full .htaccess content to replace the current file. UltraGuard will create a backup before importing.', 'ultraguard-security-suite' ),
                ],
            ] ),
            'footer'  => $this->modal_footer_save( 'ultraguard_import_htaccess' ),
        ];
    }

    public function get_scheme( $context ): array {
        $path    = ABSPATH . '.htaccess';
        $content = file_exists( $path ) ? file_get_contents( $path ) : '';

        // Extract existing custom rules block
        $custom_rules = '';
        if ( preg_match( '/# BEGIN UltraGuard Custom Rules(.*?)# END UltraGuard Custom Rules/s', $content, $m ) ) {
            $custom_rules = trim( $m[1] );
        }

        $nonce   = $this->create_nonce( 'ultraguard_admin_nonce' );
        $size    = strlen( $content );

        $templates = [
            'wp_rewrite'       => __( 'WordPress Rewrite Rules',   'ultraguard-security-suite' ),
            'security_headers' => __( 'Security Headers',          'ultraguard-security-suite' ),
            'gzip_compression' => __( 'GZIP Compression',          'ultraguard-security-suite' ),
            'browser_caching'  => __( 'Browser Caching',           'ultraguard-security-suite' ),
        ];

        $cloud_templates = (array) get_option( 'ultraguard_cloud_htaccess_rules', [] );
        foreach ( $cloud_templates as $template ) {
            if ( ! is_array( $template ) || empty( $template['id'] ) || empty( $template['title'] ) ) {
                continue;
            }

            $templates[ sanitize_key( (string) $template['id'] ) ] = sprintf(
                /* translators: Placeholder values are inserted into this string. */
                __( 'Cloud: %s', 'ultraguard-security-suite' ),
                sanitize_text_field( (string) $template['title'] )
            );
        }

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

            'header' => [
                'title'    => __( 'Custom Rules', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Edit and manage custom .htaccess directives', 'ultraguard-security-suite' ),
                /* translators: %s: string */
                'badge'    => [ 'text' => sprintf( __( '%s file size', 'ultraguard-security-suite' ), $this->format_file_size( $size ) ), 'badge_type' => 'info' ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Preview',          'ultraguard-security-suite' ), 'ultraguard_preview_htaccess',          [], 'secondary', 'dashicons-visibility'   ),
                    $this->create_ajax_button( __( 'Validate Syntax',  'ultraguard-security-suite' ), 'ultraguard_validate_htaccess_syntax',  [], 'secondary', 'dashicons-yes'          ),
                    $this->create_ajax_button( __( 'Check Conflicts',  'ultraguard-security-suite' ), 'ultraguard_check_conflicts',           [], 'secondary', 'dashicons-warning'      ),
                    $this->create_ajax_button( __( 'Backup & Save',    'ultraguard-security-suite' ), 'ultraguard_save_custom_rules',         [], 'primary',   'dashicons-saved',        __( 'Backup current .htaccess and save your custom rules?', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        // Editor — 8 columns
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Custom Rules Editor', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-editor-code',
                                'data'  => [
                                    [
                                        'type'        => 'code-editor',
                                        'name'        => 'custom_rules',
                                        'label'       => __( 'Your custom .htaccess directives', 'ultraguard-security-suite' ),
                                        'language'    => 'apache',
                                        'rows'        => 20,
                                        'default'     => $custom_rules,
                                        'placeholder' => "# Add your custom Apache directives here\n# Example:\n# Options -Indexes\n# Header set X-Frame-Options SAMEORIGIN",
                                        'description' => __( 'Rules here are wrapped in UltraGuard Custom Rules markers and inserted into your .htaccess file.', 'ultraguard-security-suite' ),
                                    ],
                                ],
                                'footer' => [
                                    'type'      => 'button-group',
                                    'alignment' => 'right',
                                    'buttons'   => [
                                        $this->create_ajax_button( __( 'Validate',    'ultraguard-security-suite' ), 'ultraguard_validate_htaccess_syntax', [], 'secondary', 'dashicons-yes'     ),
                                        $this->create_ajax_button( __( 'Optimise',    'ultraguard-security-suite' ), 'ultraguard_optimize_htaccess',        [], 'secondary', 'dashicons-performance' ),
                                        $this->create_ajax_button( __( 'Save Rules',  'ultraguard-security-suite' ), 'ultraguard_save_custom_rules',        [], 'primary',   'dashicons-saved',   __( 'Save custom rules to .htaccess?', 'ultraguard-security-suite' ) ),
                                    ],
                                ],
                            ],
                        ],

                        // Sidebar — 4 columns
                        [
                            'span'      => 4,
                            'component' => [
                                'type'    => 'grid',
                                'columns' => 1,
                                'gap'     => '20px',
                                'items'   => [
                                    // Templates
                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Insert Template', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-welcome-learn-more',
                                        'data'  => [ [ 'type' => 'list', 'items' => array_map(
                                            fn( $k, $v ) => [ 'text' => $v, 'actions' => [ $this->create_ajax_button( __( 'Insert', 'ultraguard-security-suite' ), 'ultraguard_insert_template', [ 'template' => $k ], 'secondary' ) ] ],
                                            array_keys( $templates ), $templates
                                        ) ] ],
                                    ] ],

                                    // Import / Export
                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Import / Export', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-migrate',
                                        'data'  => [ [ 'type' => 'button-group', 'alignment' => 'center', 'buttons' => [
                                            $this->create_ajax_button( __( 'Export .htaccess', 'ultraguard-security-suite' ), 'ultraguard_export_htaccess', [], 'secondary', 'dashicons-download' ),
                                            [ 'type' => 'button', 'text' => __( 'Import Rules', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-upload', 'modal' => $this->import_rules_modal() ],
                                        ] ] ],
                                    ] ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],

            'form' => [
                'enable' => true,
                'id'     => 'htaccess-custom-rules-form',
                'ajax'   => true,
                'action' => 'ultraguard_save_custom_rules',
                'nonce'  => $nonce,
                'submit' => [ 'text' => __( 'Save Custom Rules', 'ultraguard-security-suite' ), 'button_style' => 'primary' ],
            ],
        ], $context );
    }
}
