<?php

namespace UltraguardPro\modules\reputation_monitor\pages;

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

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

class ReputationMonitorDashboard extends BasePage {

    private ?ReputationCheckEngine $engine = null;

    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( 'reputation_monitor' );

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

        if ( $preview_mode ) {
            $summary = [
                'overall_status'         => 'warning',
                'sources_monitoring'     => 6,
                'currently_blacklisted'  => 1,
                'clean_since'            => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 24 ),
                'total_checks_run'       => 148,
            ];
            $results = $this->preview_results();
            $history = $this->preview_history();
            $stats   = [
                'labels'      => [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun' ],
                'clean'       => [ 5, 4, 6, 5, 7, 6 ],
                'blacklisted' => [ 1, 1, 0, 2, 1, 1 ],
            ];
        } else {
            $engine   = $this->engine();
            $summary  = $engine->run_quick_summary();
            $results  = $engine->get_check_summary();
            $history  = $engine->get_history( 50 );
            $stats    = $engine->get_stats();
        }
        $overall  = (string) $summary['overall_status'];
        /* translators: %d: integer */
        $banner   = 'clean' === $overall ? __( 'Your site is CLEAN', 'ultraguard-security-suite' ) : sprintf( __( 'Blacklist attention needed on %d source(s)', 'ultraguard-security-suite' ), (int) $summary['currently_blacklisted'] );

        $data = [
            ! $is_pro ? $this->pro_upsell_card( 'reputation_monitor' ) : [],
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'Blacklist & Reputation Monitor', 'ultraguard-security-suite' ),
                __( 'These blacklist checks, history entries, and trend charts are sample reputation records. Upgrade to watch your real domain and IP status across live providers.', 'ultraguard-security-suite' )
            ) : [],
        ];

        return [
            'type'      => 'page',
            'id'        => 'reputation-monitor-dashboard',
            'page_slug' => 'reputation-monitor',
            'header'    => [
                'title'    => __( 'Blacklist & Reputation Monitor', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Track domain and IP reputation, watch blacklist changes, and act quickly when a listing appears.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'reputation-monitor-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Check Now', 'ultraguard-security-suite' ), 'ultraguard_reputation_check_now', [], 'primary', 'dashicons-update' ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'reputation_monitor', __( 'Blacklist & Reputation Monitor', 'ultraguard-security-suite' ), array_merge( array_values( array_filter( $data ) ), [
                [
                    'type'  => 'card',
                    'title' => __( 'Overall Status', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-search',
                    'data'  => [
                        [
                            'type'    => 'html',
                            'content' => sprintf(
                                '<div class="ultraguard-reputation-status-banner is-%1$s"><h2>%2$s</h2><p>%3$s</p></div>',
                                esc_attr( 'danger' === $overall ? 'danger' : ( 'warning' === $overall ? 'warning' : 'clean' ) ),
                                esc_html( $banner ),
                                esc_html__( 'Use the source cards below to review the latest status and jump directly to delisting or manual review pages when needed.', 'ultraguard-security-suite' )
                            ),
                        ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Sources Monitoring', 'ultraguard-security-suite' ), 'value' => (int) $summary['sources_monitoring'], 'format' => 'number', 'icon' => 'dashicons-search', 'class' => 'info' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Currently Blacklisted', 'ultraguard-security-suite' ), 'value' => (int) $summary['currently_blacklisted'], 'format' => 'number', 'icon' => 'dashicons-warning', 'class' => (int) $summary['currently_blacklisted'] > 0 ? 'danger' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Clean Since', 'ultraguard-security-suite' ), 'value' => ! empty( $summary['clean_since'] ) ? $this->format_date_time( (string) $summary['clean_since'] ) : __( 'Unknown', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-yes-alt', 'class' => 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Checks Run', 'ultraguard-security-suite' ), 'value' => (int) $summary['total_checks_run'], 'format' => 'number', 'icon' => 'dashicons-chart-line', 'class' => 'info' ] ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Source Status', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-site',
                    'data'  => [
                        [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '16px',
                            'items'   => $this->build_source_grid_items( $results ),
                        ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '18px',
                    'items'   => [
                        [
                            'span'      => 7,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Status Trend (90 Days)', 'ultraguard-security-suite' ),
                                'data'  => [
                                    [
                                        'type'       => 'chart',
                                        'chart_type' => 'line',
                                        'height'     => '250px',
                                        'labels'     => $stats['labels'],
                                        'datasets'   => [
                                            [ 'label' => __( 'Clean Changes', 'ultraguard-security-suite' ), 'data' => $stats['clean'], 'borderColor' => '#157347', 'backgroundColor' => 'rgba(21,115,71,0.10)', 'fill' => true ],
                                            [ 'label' => __( 'Blacklisted Changes', 'ultraguard-security-suite' ), 'data' => $stats['blacklisted'], 'borderColor' => '#b42318', 'backgroundColor' => 'rgba(180,35,24,0.08)', 'fill' => true ],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 5,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Quick Actions', 'ultraguard-security-suite' ),
                                'data'  => [
                                    [ 'type' => 'paragraph', 'content' => __( 'Run an immediate check whenever your domain changes, DNS updates, or you want to verify a cleanup/delisting request.', 'ultraguard-security-suite' ) ],
                                    [
                                        'type'      => 'button-group',
                                        'alignment' => 'left',
                                        'buttons'   => [
                                            [
                                                'type'         => 'button',
                                                'text'         => __( 'Run Full Check', 'ultraguard-security-suite' ),
                                                'button_style' => 'primary',
                                                'icon'         => 'dashicons-update',
                                                'ajax'         => [
                                                    'action' => 'ultraguard_reputation_check_now',
                                                    'nonce'  => $nonce,
                                                ],
                                            ],
                                            [
                                                'type'         => 'button',
                                                'text'         => __( 'Review Settings', 'ultraguard-security-suite' ),
                                                'button_style' => 'secondary',
                                                'icon'         => 'dashicons-admin-settings',
                                                'url'          => $this->get_page_url( 'reputation-monitor-settings' ),
                                            ],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Status Change History', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-backup',
                    'data'  => [
                        [
                            'type'       => 'data-table',
                            'id'         => 'reputation-monitor-history',
                            'columns'    => [
                                'source'    => [ 'title' => __( 'Source', 'ultraguard-security-suite' ) ],
                                'target'    => [ 'title' => __( 'Target', 'ultraguard-security-suite' ) ],
                                'change'    => [ 'title' => __( 'Old Status → New Status', 'ultraguard-security-suite' ) ],
                                'threat'    => [ 'title' => __( 'Threat Type', 'ultraguard-security-suite' ) ],
                                'datetime'  => [ 'title' => __( 'Date / Time', 'ultraguard-security-suite' ), 'sortable' => true ],
                            ],
                            'data'       => $this->build_history_rows( $history ),
                            'searchable' => true,
                            'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
                        ],
                    ],
                ],
            ] ) ),
            'form'      => [ 'enable' => false ],
            'nonce'     => $nonce,
        ];
    }

    private function build_source_grid_items( array $results ): array {
        if ( empty( $results ) ) {
            return [
                [
                    'span'      => 12,
                    'component' => [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'title'      => __( 'No reputation checks yet', 'ultraguard-security-suite' ),
                        'message'    => __( 'Run a reputation check to populate source cards.', 'ultraguard-security-suite' ),
                    ],
                ],
            ];
        }

        $engine = $this->engine();
        $items  = [];

        foreach ( $results as $row ) {
            $status = (string) ( $row['status'] ?? 'pending' );
            $badge_type = 'secondary';
            if ( 'blacklisted' === $status ) {
                $badge_type = 'danger';
            } elseif ( 'suspicious' === $status ) {
                $badge_type = 'warning';
            } elseif ( 'clean' === $status ) {
                $badge_type = 'success';
            }
            $items[] = [
                'span'       => 4,
                'responsive' => [ 'md' => 6, 'sm' => 12 ],
                'component'  => [
                    'type'  => 'card',
                    'title' => (string) ( $row['source_name'] ?? $row['source_id'] ?? '' ),
                    'badge' => [
                        'text'       => strtoupper( $status ),
                        'badge_type' => $badge_type,
                    ],
                    'data'  => [
                        /* translators: %s: string */
                        [ 'type' => 'paragraph', 'content' => sprintf( __( 'Last checked: %s', 'ultraguard-security-suite' ), ! empty( $row['last_checked_at'] ) ? $this->format_date_time( (string) $row['last_checked_at'] ) : __( 'Never', 'ultraguard-security-suite' ) ) ],
                        /* translators: %s: string */
                        [ 'type' => 'paragraph', 'content' => sprintf( __( 'Target: %s', 'ultraguard-security-suite' ), (string) ( $row['target'] ?? '' ) ) ],
                        [ 'type' => 'paragraph', 'content' => (string) ( $row['details'] ?? '' ) ],
                        [
                            'type'      => 'button-group',
                            'alignment' => 'left',
                            'buttons'   => [
                                [
                                    'type'         => 'button',
                                    'text'         => __( 'Check Now', 'ultraguard-security-suite' ),
                                    'button_style' => 'secondary',
                                    'icon'         => 'dashicons-update',
                                    'ajax'         => [
                                        'action' => 'ultraguard_reputation_check_now',
                                        'nonce'  => $this->create_nonce( 'ultraguard_admin_nonce' ),
                                    ],
                                ],
                                [
                                    'type'         => 'button',
                                    'text'         => __( 'Request Delisting', 'ultraguard-security-suite' ),
                                    'button_style' => 'primary',
                                    'icon'         => 'dashicons-external',
                                    'url'          => $engine->get_delisting_url( (string) ( $row['source_id'] ?? '' ) ),
                                    'target'       => '_blank',
                                ],
                            ],
                        ],
                    ],
                ],
            ];
        }

        return $items;
    }

    private function build_history_rows( array $history ): array {
        $rows = [];

        foreach ( $history as $index => $row ) {
            $rows[] = [
                'id'       => 'reputation-history-' . $index,
                'source'   => esc_html( (string) ( $row['source_id'] ?? '' ) ),
                'target'   => esc_html( (string) ( $row['target'] ?? '' ) ),
                'change'   => esc_html( (string) ( $row['old_status'] ?? __( 'unknown', 'ultraguard-security-suite' ) ) . ' → ' . (string) ( $row['new_status'] ?? '' ) ),
                'threat'   => esc_html( (string) ( $row['threat_type'] ?? '' ) ),
                'datetime' => esc_html( $this->format_date_time( (string) ( $row['created_at'] ?? '' ) ) ),
            ];
        }

        return $rows;
    }

    private function engine(): ReputationCheckEngine {
        if ( null === $this->engine ) {
            $this->engine = new ReputationCheckEngine( $this->plugin );
        }

        return $this->engine;
    }

    private function preview_results(): array {
        return [
            [
                'source_name'     => 'Google Safe Browsing',
                'source_id'       => 'google_safe_browsing',
                'status'          => 'clean',
                'last_checked_at' => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 2 ),
                'target'          => home_url(),
                'details'         => __( 'No unsafe content flags detected.', 'ultraguard-security-suite' ),
            ],
            [
                'source_name'     => 'Spamhaus DBL',
                'source_id'       => 'spamhaus',
                'status'          => 'blacklisted',
                'last_checked_at' => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 3 ),
                'target'          => wp_parse_url( home_url(), PHP_URL_HOST ),
                'details'         => __( 'Domain listed for recent phishing-like traffic patterns. Review delisting workflow.', 'ultraguard-security-suite' ),
            ],
            [
                'source_name'     => 'Norton Safe Web',
                'source_id'       => 'norton',
                'status'          => 'clean',
                'last_checked_at' => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 4 ),
                'target'          => home_url(),
                'details'         => __( 'Trusted storefront reputation confirmed.', 'ultraguard-security-suite' ),
            ],
        ];
    }

    private function preview_history(): array {
        return [
            [
                'source_name'   => 'Spamhaus DBL',
                'target'        => wp_parse_url( home_url(), PHP_URL_HOST ),
                'old_status'    => 'clean',
                'new_status'    => 'blacklisted',
                'threat_type'   => 'phishing',
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 2 ),
            ],
            [
                'source_name'   => 'Google Safe Browsing',
                'target'        => home_url(),
                'old_status'    => 'warning',
                'new_status'    => 'clean',
                'threat_type'   => 'malware',
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 10 ),
            ],
        ];
    }
}
