<?php

namespace UltraguardPro\modules\uptime_monitor\pages;

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

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

class UptimeMonitorDashboard extends BasePage {

    private ?UptimeCheckEngine $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( 'uptime_monitor' );

        if ( $preview_mode ) {
            $status      = 'warning';
            $uptime24    = 99.82;
            $uptime7d    = 99.37;
            $uptime30d   = 99.42;
            $avgResponse = 624;
            $ssl         = [
                'is_valid'      => true,
                'expiry_date'   => gmdate( 'Y-m-d H:i:s', time() + DAY_IN_SECONDS * 47 ),
                'days_remaining'=> 47,
                'issuer'        => 'Let\'s Encrypt R11',
            ];
            $response    = [ 'labels' => [ '00:00', '06:00', '12:00', '18:00', '23:00' ], 'values' => [ 540, 580, 690, 610, 600 ] ];
            $dailyUptime = [ 'labels' => [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ], 'values' => [ 100, 99.4, 99.9, 98.7, 100, 99.8, 99.6 ] ];
            $incidents   = $this->preview_incidents();
        } else {
            $engine       = $this->engine();
            $status       = $engine->get_current_status();
            $uptime24     = $engine->get_uptime_percentage( 24 );
            $uptime7d     = $engine->get_uptime_percentage( 24 * 7 );
            $uptime30d    = $engine->get_uptime_percentage( 24 * 30 );
            $avgResponse  = $engine->get_average_response_time( 24 );
            $ssl          = $engine->get_ssl_status();
            $response     = $engine->get_response_chart();
            $dailyUptime  = $engine->get_daily_uptime_chart();
            $incidents    = $engine->get_recent_incidents( 20 );
        }

        $data = [
            ! $is_pro ? $this->pro_upsell_card( 'uptime_monitor' ) : [],
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'Uptime & SSL Monitor', 'ultraguard-security-suite' ),
                __( 'This status board is showing curated uptime incidents, response-time trends, and SSL health examples. Upgrade to monitor your real endpoints and certificate lifecycle.', 'ultraguard-security-suite' )
            ) : [],
        ];

        return [
            'type'      => 'page',
            'id'        => 'uptime-monitor-dashboard',
            'page_slug' => 'uptime-monitor',
            'header'    => [
                'title'    => __( 'Uptime & SSL Monitor', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Track uptime, response speed, and SSL health before users notice a problem.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'uptime-monitor-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Check Now', 'ultraguard-security-suite' ), 'ultraguard_uptime_check_now', [], 'primary', 'dashicons-update' ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'uptime_monitor', __( 'Uptime & SSL Monitor', 'ultraguard-security-suite' ), array_merge( array_values( array_filter( $data ) ), [
                [
                    'type'  => 'card',
                    'title' => __( 'Current Status', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-clock',
                    'data'  => [
                        [
                            'type'    => 'html',
                            'content' => sprintf(
                                '<div class="ultraguard-uptime-status ultraguard-uptime-status-%1$s"><span class="ultraguard-uptime-dot"></span><strong>%2$s</strong></div>',
                                esc_attr( sanitize_html_class( $status ) ),
                                esc_html( strtoupper( $status ) )
                            ),
                        ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Uptime 24h', 'ultraguard-security-suite' ), 'value' => round( $uptime24, 2 ), 'format' => 'percent', 'icon' => 'dashicons-clock', 'class' => $uptime24 >= 99 ? 'success' : 'warning' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Uptime 7d', 'ultraguard-security-suite' ), 'value' => round( $uptime7d, 2 ), 'format' => 'percent', 'icon' => 'dashicons-chart-line', 'class' => $uptime7d >= 99 ? 'success' : 'warning' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Uptime 30d', 'ultraguard-security-suite' ), 'value' => round( $uptime30d, 2 ), 'format' => 'percent', 'icon' => 'dashicons-chart-bar', 'class' => $uptime30d >= 99 ? 'success' : 'warning' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Avg Response (ms)', 'ultraguard-security-suite' ), 'value' => round( $avgResponse, 2 ), 'format' => 'number', 'icon' => 'dashicons-performance', 'class' => $avgResponse > 2500 ? 'warning' : 'info' ] ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'SSL Status', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-lock',
                    'data'  => [
                        /* translators: %1$s: string */
                        [ 'type' => 'paragraph', 'content' => sprintf( __( 'Certificate: %1$s', 'ultraguard-security-suite' ), ! empty( $ssl['is_valid'] ) ? __( 'Valid', 'ultraguard-security-suite' ) : __( 'Invalid', 'ultraguard-security-suite' ) ) ],
                        /* translators: %s: string */
                        [ 'type' => 'paragraph', 'content' => sprintf( __( 'Expiry Date: %s', 'ultraguard-security-suite' ), ! empty( $ssl['expiry_date'] ) ? $this->format_date_time( (string) $ssl['expiry_date'] ) : __( 'Unknown', 'ultraguard-security-suite' ) ) ],
                        /* translators: %d: integer */
                        [ 'type' => 'paragraph', 'content' => sprintf( __( 'Days Remaining: %d', 'ultraguard-security-suite' ), (int) ( $ssl['days_remaining'] ?? 0 ) ) ],
                        /* translators: %s: string */
                        [ 'type' => 'paragraph', 'content' => sprintf( __( 'Issuer: %s', 'ultraguard-security-suite' ), (string) ( $ssl['issuer'] ?? __( 'Unknown', 'ultraguard-security-suite' ) ) ) ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '18px',
                    'items'   => [
                        [
                            'span'      => 7,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Response Time (24h)', 'ultraguard-security-suite' ),
                                'data'  => [
                                    [
                                        'type'       => 'chart',
                                        'chart_type' => 'line',
                                        'height'     => '250px',
                                        'labels'     => $response['labels'],
                                        'datasets'   => [
                                            [ 'label' => __( 'Response Time', 'ultraguard-security-suite' ), 'data' => $response['values'], 'borderColor' => '#155eef', 'backgroundColor' => 'rgba(21,94,239,0.08)', 'fill' => true ],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 5,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Uptime (30 Days)', 'ultraguard-security-suite' ),
                                'data'  => [
                                    [
                                        'type'       => 'chart',
                                        'chart_type' => 'bar',
                                        'height'     => '250px',
                                        'labels'     => $dailyUptime['labels'],
                                        'datasets'   => [
                                            [ 'label' => __( 'Uptime %', 'ultraguard-security-suite' ), 'data' => $dailyUptime['values'], 'backgroundColor' => '#157347' ],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Recent Incidents', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-warning',
                    'data'  => [
                        [
                            'type'       => 'data-table',
                            'id'         => 'uptime-monitor-incidents',
                            'columns'    => [
                                'status'        => [ 'title' => __( 'Status', 'ultraguard-security-suite' ) ],
                                'time'          => [ 'title' => __( 'Time', 'ultraguard-security-suite' ) ],
                                'response_code' => [ 'title' => __( 'Response Code', 'ultraguard-security-suite' ) ],
                                'response_time' => [ 'title' => __( 'Response Time', 'ultraguard-security-suite' ) ],
                                'error'         => [ 'title' => __( 'Error', 'ultraguard-security-suite' ) ],
                            ],
                            'data'       => $this->build_incident_rows( $incidents ),
                            'searchable' => true,
                            'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
                        ],
                    ],
                ],
            ] ) ),
            'form'      => [ 'enable' => false ],
        ];
    }

    private function build_incident_rows( array $incidents ): array {
        $rows = [];

        foreach ( $incidents as $index => $incident ) {
            $rows[] = [
                'id'            => 'uptime-incident-' . $index,
                'status'        => esc_html( strtoupper( (string) ( $incident['status'] ?? '' ) ) ),
                'time'          => esc_html( $this->format_date_time( (string) ( $incident['created_at'] ?? '' ) ) ),
                'response_code' => (int) ( $incident['response_code'] ?? 0 ),
                'response_time' => esc_html( (string) ( $incident['response_time'] ?? 0 ) . ' ms' ),
                'error'         => esc_html( (string) ( $incident['error_message'] ?? '' ) ),
            ];
        }

        return $rows;
    }

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

        return $this->engine;
    }

    private function preview_incidents(): array {
        return [
            [
                'status'        => 'down',
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS ),
                'response_code' => 503,
                'response_time' => 0,
                'error_message' => 'Upstream timeout during payment gateway sync.',
            ],
            [
                'status'        => 'slow',
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 3 ),
                'response_code' => 200,
                'response_time' => 3820,
                'error_message' => 'Checkout page latency crossed the alert threshold.',
            ],
        ];
    }
}
