<?php
/**
 * HtaccessDashboard — Main .htaccess overview page.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

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

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

class HtaccessDashboard extends BasePage {

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

    public function get_scheme( $context ): array {
        $path     = ABSPATH . '.htaccess';
        $exists   = file_exists( $path );
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- direct writability check for dashboard status only.
        $writable = $exists && is_writable( $path );
        $size     = $exists ? filesize( $path ) : 0;
        $modified = $exists ? filemtime( $path ) : null;

        $backup_dir   = trailingslashit( wp_upload_dir()['basedir'] ) . 'ultraguard-htaccess-backups/';
        $backup_files = is_dir( $backup_dir ) ? glob( $backup_dir . 'htaccess-*.txt' ) : [];
        $backup_count = $backup_files ? count( $backup_files ) : 0;

        $score = 0;
        if ( $exists ) {
            $content = file_get_contents( $path );
            foreach ( [ 'Options -Indexes', 'X-Frame-Options', 'X-Content-Type-Options', 'BEGIN UltraGuard' ] as $m ) {
                if ( str_contains( $content, $m ) ) { $score += 25; }
            }
        }

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

        // ── Chart data ────────────────────────────────────────────────────────
        $db         = $this->plugin->modules->get_db_tables();
        $change_tbl = $db ? $db->get_table( 'htaccess_change_log' ) : null;

        // .htaccess change history — all modifications over last 30 days
        $change_trend = $change_tbl
            ? $change_tbl->get_chart_data( 'created_at', 'id', 'day', [], 30 )
            : [ 'labels' => [], 'data' => [] ];

        // Breakdown by change type (security_rule / custom / backup / manual)
        $change_type_chart = $change_tbl
            ? $change_tbl->get_pie_chart_data( 'type', 'id', 'COUNT', [], 6 )
            : [ 'labels' => [], 'data' => [], 'colors' => [] ];

        $features = [
            'disable_directory_listing' => \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_feature_disable_directory_listing', false ),
            'protect_wp_config'         => \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_feature_protect_wp_config', false ),
            'protect_wp_includes'       => \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_feature_protect_wp_includes', false ),
            'block_xmlrpc'              => \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_feature_block_xmlrpc', false ),
            'security_headers'          => \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_feature_security_headers', false ),
        ];

        return apply_filters( 'ultraguard_htaccess_dashboard_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-htaccess-dashboard',
            'page_slug' => 'htaccess',
            'class'     => 'ultraguard-htaccess-dashboard-page',

            'header' => [
                'title'    => __( '.htaccess Manager', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Manage your .htaccess file, security rules and access protection', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: integer */
                    'text'       => sprintf( __( 'Security Score: %d%%', 'ultraguard-security-suite' ), $score ),
                    'badge_type' => $score >= 75 ? 'success' : ( $score >= 50 ? 'warning' : 'danger' ),
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Refresh Stats',   'ultraguard-security-suite' ), 'ultraguard_refresh_htaccess_stats', [], 'secondary', 'dashicons-update' ),
                    $this->create_ajax_button( __( 'Create Backup',   'ultraguard-security-suite' ), 'ultraguard_create_htaccess_backup', [], 'primary',   'dashicons-backup', __( 'Create a backup of the current .htaccess file?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Verify File',     'ultraguard-security-suite' ), 'ultraguard_verify_htaccess',       [], 'secondary', 'dashicons-yes'    ),
                    $this->create_ajax_button( __( 'Download',        'ultraguard-security-suite' ), 'ultraguard_download_htaccess',     [], 'secondary', 'dashicons-download' ),
                ],
            ],

            'data' => [
                // ── Stats row ──────────────────────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'File Status',     'ultraguard-security-suite' ), 'value' => $exists   ? __( 'Exists',   'ultraguard-security-suite' ) : __( 'Missing', 'ultraguard-security-suite' ),   'format' => 'text',   'icon' => 'dashicons-media-text',   'class' => $exists   ? 'success' : 'danger'  ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Writable',        'ultraguard-security-suite' ), 'value' => $writable ? __( 'Yes',      'ultraguard-security-suite' ) : __( 'No',      'ultraguard-security-suite' ),   'format' => 'text',   'icon' => 'dashicons-edit',         'class' => $writable ? 'success' : 'warning' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'File Size',       'ultraguard-security-suite' ), 'value' => $this->format_file_size( $size ),                                                      'format' => 'text',   'icon' => 'dashicons-media-code',   'class' => 'info'                            ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Backups Stored',  'ultraguard-security-suite' ), 'value' => $backup_count,                                                                          'format' => 'number', 'icon' => 'dashicons-backup',       'class' => $backup_count > 0 ? 'success' : 'secondary' ] ],
                    ],
                ],

                // ── Change history charts: trend + type breakdown ──────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( '.htaccess Changes — Last 30 Days', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-line',
                                'data'  => empty( $change_trend['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No changes recorded in the last 30 days.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'bar',
                                        'height'         => '200px',
                                        'labels'         => $change_trend['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'Changes', 'ultraguard-security-suite' ),
                                                'data'            => $change_trend['data'],
                                                'backgroundColor' => 'rgba(99,102,241,0.65)',
                                                'borderColor'     => '#6366f1',
                                                'borderWidth'     => 1,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Date', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Changes', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Changes by Type', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-pie',
                                'data'  => empty( $change_type_chart['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No change type data yet.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'doughnut',
                                        'height'         => '200px',
                                        'labels'         => $change_type_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'data'            => $change_type_chart['data'],
                                                'backgroundColor' => $change_type_chart['colors'],
                                                'borderWidth'     => 2,
                                            ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],

                // ── Main layout: content + sidebar ──────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'    => 'grid',
                                'columns' => 1,
                                'gap'     => '20px',
                                'items'   => [
                                    // Security score card
                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Security Score', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-shield',
                                        'data'  => [
                                            [ 'type' => 'progress', 'value' => $score, 'max' => 100, 'progress_type' => 'bar', 'status' => $score >= 75 ? 'success' : ( $score >= 50 ? 'warning' : 'danger' ), 'show_value' => true, 'animated' => false ],
                                            [ 'type' => 'list', 'items' => [
                                                [ 'icon' => 'dashicons-minus-alt', 'text' => __( 'Directory Listing Disabled', 'ultraguard-security-suite' ), 'badge' => [ 'text' => str_contains( $exists ? file_get_contents( $path ) : '', 'Options -Indexes' ) ? __( 'Protected', 'ultraguard-security-suite' ) : __( 'Not Set', 'ultraguard-security-suite' ), 'badge_type' => str_contains( $exists ? file_get_contents( $path ) : '', 'Options -Indexes' ) ? 'success' : 'secondary' ] ],
                                                [ 'icon' => 'dashicons-lock',      'text' => __( 'Security Headers',          'ultraguard-security-suite' ), 'badge' => [ 'text' => str_contains( $exists ? file_get_contents( $path ) : '', 'X-Frame-Options' )  ? __( 'Active', 'ultraguard-security-suite' )    : __( 'Not Set', 'ultraguard-security-suite' ), 'badge_type' => str_contains( $exists ? file_get_contents( $path ) : '', 'X-Frame-Options' )  ? 'success' : 'secondary' ] ],
                                                [ 'icon' => 'dashicons-shield-alt','text' => __( 'UltraGuard Rules',           'ultraguard-security-suite' ), 'badge' => [ 'text' => str_contains( $exists ? file_get_contents( $path ) : '', 'UltraGuard' )       ? __( 'Present', 'ultraguard-security-suite' )  : __( 'None',    'ultraguard-security-suite' ), 'badge_type' => str_contains( $exists ? file_get_contents( $path ) : '', 'UltraGuard' )       ? 'success' : 'secondary' ] ],
                                            ] ],
                                        ],
                                    ] ],

                                    // Quick actions
                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Quick Actions', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-admin-tools',
                                        'data'  => [ [
                                            'type'      => 'button-group',
                                            'alignment' => 'center',
                                            'buttons'   => [
                                                $this->create_url_button(  __( 'Security Rules',  'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=htaccess-security-rules' ), 'primary',   'dashicons-shield-alt'  ),
                                                $this->create_url_button(  __( 'Custom Rules',    'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=htaccess-custom-rules' ), 'secondary', 'dashicons-editor-code' ),
                                                $this->create_url_button(  __( 'View Backups',    'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=htaccess-backups' ), 'secondary', 'dashicons-backup'      ),
                                                $this->create_ajax_button( __( 'Clear Cache',     'ultraguard-security-suite' ), 'ultraguard_clear_htaccess_cache', [], 'secondary', 'dashicons-trash' ),
                                            ],
                                        ] ],
                                    ] ],
                                ],
                            ],
                        ],

                        // Sidebar
                        [
                            'span'      => 4,
                            'component' => [
                                'type'    => 'grid',
                                'columns' => 1,
                                'gap'     => '20px',
                                'items'   => [
                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'File Information', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-media-code',
                                        'data'  => [ [ 'type' => 'list', 'items' => [
                                            [ 'text' => __( 'File Path',    'ultraguard-security-suite' ), 'badge' => [ 'text' => ABSPATH . '.htaccess',                                                  'badge_type' => 'secondary' ] ],
                                            [ 'text' => __( 'Last Modified','ultraguard-security-suite' ), 'badge' => [ 'text' => $modified ? date_i18n( 'Y-m-d H:i', $modified ) : '—',                 'badge_type' => 'info'      ] ],
                                            [ 'text' => __( 'File Size',    'ultraguard-security-suite' ), 'badge' => [ 'text' => $this->format_file_size( $size ),                                       'badge_type' => 'secondary' ] ],
                                            [ 'text' => __( 'Backups',      'ultraguard-security-suite' ), 'badge' => [ 'text' => $backup_count . ' ' . __( 'stored', 'ultraguard-security-suite' ),                 'badge_type' => 'info'      ] ],
                                        ] ] ],
                                    ] ],

                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Active Security Features', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-yes-alt',
                                        'data'  => [ [ 'type' => 'list', 'items' => array_map( fn( $k, $v ) => [
                                            'icon'  => $v ? 'dashicons-yes' : 'dashicons-no-alt',
                                            'text'  => ucwords( str_replace( '_', ' ', $k ) ),
                                            'badge' => [ 'text' => $v ? __( 'On', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => $v ? 'success' : 'secondary' ],
                                        ], array_keys( $features ), $features ) ] ],
                                        'footer' => $this->create_url_button( __( 'Manage Rules', 'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=htaccess-security-rules' ), 'primary', 'dashicons-shield-alt' ),
                                    ] ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],

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