<?php

namespace UltraguardPro\modules\woo_security\pages;

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

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

class WooSecurityDashboard extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $is_pro = \UltraguardPro\support\LicenseInfo::instance()->isPro();
        $preview_mode = $this->is_soft_gated_module_preview( 'woo_security' );

        if ( $preview_mode ) {
            $settings = [
                'woo_security_skimmer_detection' => true,
                'woo_security_strict_csp'        => true,
                'woo_security_checkout_honeypot' => true,
                'woo_security_secure_headers'    => true,
                'woo_security_alert_on_skimmer'  => true,
            ];
            $results = $this->preview_results();
            $blocked = 27;
        } else {
            $settings = $this->settings->get_module_settings( 'woo_security' );
            $table    = $this->plugin->modules->get_db_tables()->get_table( 'skimmer_scan_results' );
            $results  = $table && method_exists( $table, 'get_recent' ) ? $table->get_recent( 50 ) : [];
            $blocked  = \UltraguardPro\modules\woo_security\WooSecurityModule::get_bot_orders_blocked_count();
        }
        $score    = $this->security_score( $settings );

        $data = [
            ! $is_pro ? $this->pro_upsell_card( 'woo_security' ) : [],
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'WooCommerce Security Mode', 'ultraguard-security-suite' ),
                __( 'The skimmer findings, bot-order counts, and checkout hardening status shown here are sample storefront records. Upgrade to scan your own WooCommerce checkout and protect live customer traffic.', 'ultraguard-security-suite' )
            ) : [],
        ];

        return [
            'type'      => 'page',
            'id'        => 'woo-security-dashboard',
            'page_slug' => 'woo-security',
            'header'    => [
                'title'    => __( 'WooCommerce Security Mode', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Store-aware protections for checkout, cart, account, and payment flows.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'woo-security-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Scan Now', 'ultraguard-security-suite' ), 'ultraguard_woo_run_skimmer_scan', [], 'primary', 'dashicons-search' ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'woo_security', __( 'WooCommerce Security Mode', 'ultraguard-security-suite' ), array_merge( array_values( array_filter( $data ) ), [
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'WooCommerce Version', 'ultraguard-security-suite' ), 'value' => defined( 'WC_VERSION' ) ? WC_VERSION : __( 'Unknown', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-cart', 'class' => 'info' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Store URL', 'ultraguard-security-suite' ), 'value' => home_url(), 'format' => 'text', 'icon' => 'dashicons-admin-site', 'class' => 'secondary' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Security Score', 'ultraguard-security-suite' ), 'value' => $score, 'format' => 'number', 'icon' => 'dashicons-shield-alt', 'class' => $score > 79 ? 'success' : 'warning' ] ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => $this->status_card( __( 'Card Skimmer Detection', 'ultraguard-security-suite' ), ! empty( $settings['woo_security_skimmer_detection'] ) ) ],
                        [ 'span' => 3, 'component' => $this->status_card( __( 'Checkout CSP', 'ultraguard-security-suite' ), ! empty( $settings['woo_security_strict_csp'] ) ) ],
                        [ 'span' => 3, 'component' => $this->status_card( __( 'Honeypot Protection', 'ultraguard-security-suite' ), ! empty( $settings['woo_security_checkout_honeypot'] ) ) ],
                        [ 'span' => 3, 'component' => $this->status_card( __( 'Secure Headers', 'ultraguard-security-suite' ), ! empty( $settings['woo_security_secure_headers'] ) ) ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Last Skimmer Scan', 'ultraguard-security-suite' ),
                    'data'  => [
                        [ 'type' => 'html', 'content' => '<p><strong>' . esc_html__( 'Timestamp:', 'ultraguard-security-suite' ) . '</strong> ' . esc_html( ! empty( $results[0]['created_at'] ) ? $this->format_date_time( (string) $results[0]['created_at'] ) : __( 'Never', 'ultraguard-security-suite' ) ) . '</p>' ],
                        [ 'type' => 'html', 'content' => '<p><strong>' . esc_html__( 'Threats found:', 'ultraguard-security-suite' ) . '</strong> ' . esc_html( (string) count( $results ) ) . '</p>' ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Bot Orders Blocked', 'ultraguard-security-suite' ), 'value' => $blocked, 'format' => 'number', 'icon' => 'dashicons-dismiss', 'class' => $blocked > 0 ? 'warning' : 'secondary' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Scan Threats Found', 'ultraguard-security-suite' ), 'value' => count( $results ), 'format' => 'number', 'icon' => 'dashicons-warning', 'class' => count( $results ) > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last Scan Time', 'ultraguard-security-suite' ), 'value' => ! empty( $results[0]['created_at'] ) ? $this->format_date_time( (string) $results[0]['created_at'] ) : __( 'Never', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-clock', 'class' => 'info' ] ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Scan Results', 'ultraguard-security-suite' ),
                    'data'  => [
                        [
                            'type'       => 'data-table',
                            'id'         => 'woo-security-scan-results',
                            'columns'    => [
                                'file'      => [ 'title' => __( 'File', 'ultraguard-security-suite' ) ],
                                'finding'   => [ 'title' => __( 'Finding Type', 'ultraguard-security-suite' ) ],
                                'severity'  => [ 'title' => __( 'Severity', 'ultraguard-security-suite' ) ],
                                'detected'  => [ 'title' => __( 'First Detected', 'ultraguard-security-suite' ) ],
                            ],
                            'data'       => $this->build_rows( $results ),
                            'searchable' => true,
                            'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
                        ],
                    ],
                ],
            ] ) ),
            'form'      => [ 'enable' => false ],
        ];
    }

    private function status_card( string $title, bool $enabled ): array {
        return [
            'type'  => 'card',
            'title' => $title,
            'data'  => [
                [
                    'type'       => 'alert-box',
                    'alert_type' => $enabled ? 'success' : 'warning',
                    'message'    => $enabled ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ),
                ],
            ],
        ];
    }

    private function build_rows( array $results ): array {
        $rows = [];
        foreach ( $results as $index => $row ) {
            $rows[] = [
                'id'       => 'scan-result-' . $index,
                'file'     => esc_html( basename( (string) $row['file_path'] ) ),
                'finding'  => esc_html( (string) $row['finding_type'] ),
                'severity' => [ 'content' => esc_html( ucfirst( (string) $row['severity'] ) ), 'class' => in_array( $row['severity'], [ 'critical', 'high' ], true ) ? 'danger' : 'warning' ],
                'detected' => esc_html( ! empty( $row['created_at'] ) ? $this->format_date_time( (string) $row['created_at'] ) : __( 'Unknown', 'ultraguard-security-suite' ) ),
            ];
        }

        return $rows;
    }

    private function security_score( array $settings ): int {
        $score = 40;
        foreach ( [ 'woo_security_skimmer_detection', 'woo_security_strict_csp', 'woo_security_checkout_honeypot', 'woo_security_secure_headers', 'woo_security_alert_on_skimmer' ] as $flag ) {
            if ( ! empty( $settings[ $flag ] ) ) {
                $score += 12;
            }
        }

        return min( 100, $score );
    }

    private function preview_results(): array {
        return [
            [
                'file_path'    => WP_CONTENT_DIR . '/plugins/checkout-helper/assets/js/cart-widget.js',
                'finding_type' => 'Injected Card Skimmer Signature',
                'severity'     => 'critical',
                'created_at'   => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 2 ),
            ],
            [
                'file_path'    => WP_CONTENT_DIR . '/themes/storefront-child/checkout/tracking.js',
                'finding_type' => 'Unexpected Remote Script',
                'severity'     => 'high',
                'created_at'   => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 5 ),
            ],
        ];
    }
}
