<?php

namespace UltraguardPro\modules\api_security\pages;

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

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

class ApiSecurityDashboard extends BasePage {

    private ?ApiSecurityEngine $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( 'api_security' );

        if ( $preview_mode ) {
            $stats = [
                'total_api_keys'    => 4,
                'rest_requests_24h' => 1268,
                'blocked_24h'       => 37,
                'xmlrpc_calls_24h'  => 19,
            ];
            $rows = $this->preview_key_records();
            $logs = $this->preview_log_records();
        } else {
            $stats     = $this->engine()->get_stats();
            $keys      = $this->plugin->modules->get_db_tables()->get_table( 'api_keys' );
            $log_table = $this->plugin->modules->get_db_tables()->get_table( 'api_request_log' );
            $rows      = $keys && method_exists( $keys, 'get_recent_keys' ) ? $keys->get_recent_keys( 25 ) : [];
            $logs      = $log_table && method_exists( $log_table, 'get_recent_requests' ) ? $log_table->get_recent_requests( 25, 1 ) : [];
        }
        $nonce     = $this->create_nonce( 'ultraguard_admin_nonce' );

        $data = [
            ! $is_pro ? $this->pro_upsell_card( 'api_security' ) : [],
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'REST API & XML-RPC Security', 'ultraguard-security-suite' ),
                __( 'These API keys, request logs, and blocked requests are sample records from a protected WordPress site. Upgrade to monitor your live API surface and manage real keys.', 'ultraguard-security-suite' )
            ) : [],

            [
                'type'    => 'grid',
                'columns' => 12,
                'gap'     => '16px',
                'items'   => [
                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total API Keys', 'ultraguard-security-suite' ), 'value' => (int) ( $stats['total_api_keys'] ?? 0 ), 'format' => 'number', 'icon' => 'dashicons-admin-network', 'class' => 'info' ] ],
                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'REST Requests (24h)', 'ultraguard-security-suite' ), 'value' => (int) ( $stats['rest_requests_24h'] ?? 0 ), 'format' => 'number', 'icon' => 'dashicons-rest-api', 'class' => 'info' ] ],
                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked (24h)', 'ultraguard-security-suite' ), 'value' => (int) ( $stats['blocked_24h'] ?? 0 ), 'format' => 'number', 'icon' => 'dashicons-shield', 'class' => ( (int) ( $stats['blocked_24h'] ?? 0 ) > 0 ? 'warning' : 'success' ) ] ],
                    [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'XML-RPC Calls (24h)', 'ultraguard-security-suite' ), 'value' => (int) ( $stats['xmlrpc_calls_24h'] ?? 0 ), 'format' => 'number', 'icon' => 'dashicons-rss', 'class' => 'secondary' ] ],
                ],
            ],
            [
                'type'  => 'card',
                'title' => __( 'Create New API Key', 'ultraguard-security-suite' ),
                'icon'  => 'dashicons-plus-alt',
                'data'  => [
                    [ 'type' => 'paragraph', 'content' => __( 'Generate a restricted key for external services, headless apps, or integrations. The raw key will only be shown once after creation.', 'ultraguard-security-suite' ) ],
                    [ 'type' => 'text', 'name' => 'api-key-name', 'label' => __( 'Key name', 'ultraguard-security-suite' ), 'value' => '', 'placeholder' => __( 'Storefront integration', 'ultraguard-security-suite' ) ],
                    [ 'type' => 'text', 'name' => 'api-key-route', 'label' => __( 'Allowed route regex', 'ultraguard-security-suite' ), 'value' => '', 'placeholder' => '/wc/v3/|/wp/v2/posts' ],
                    [ 'type' => 'number', 'name' => 'api-key-rate', 'label' => __( 'Rate limit / min', 'ultraguard-security-suite' ), 'value' => 60, 'min' => 0 ],
                    [ 'type' => 'text', 'name' => 'api-key-expiry', 'label' => __( 'Expiry', 'ultraguard-security-suite' ), 'value' => '', 'placeholder' => '2026-12-31 23:59:59' ],
                    [
                        'type'         => 'button',
                        'id'           => 'ultraguard-api-create-key',
                        'text'         => __( 'Generate API Key', 'ultraguard-security-suite' ),
                        'button_style' => 'primary',
                        'icon'         => 'dashicons-admin-network',
                    ],
                    [ 'type' => 'paragraph', 'content' => __( 'After generation, copy the key immediately and store it in a secure password manager.', 'ultraguard-security-suite' ) ],
                    [ 'type' => 'html', 'content' => '<div id="ultraguard-api-generated-key" class="ultraguard-api-generated-key is-hidden"></div>' ],
                ],
            ],
            [
                'type'  => 'card',
                'title' => __( 'Managed API Keys', 'ultraguard-security-suite' ),
                'icon'  => 'dashicons-lock',
                'data'  => [
                    [
                        'type'       => 'data-table',
                        'id'         => 'api-security-keys-table',
                        'columns'    => [
                            'key_name'   => [ 'title' => __( 'Key Name', 'ultraguard-security-suite' ) ],
                            'prefix'     => [ 'title' => __( 'Prefix', 'ultraguard-security-suite' ) ],
                            'user'       => [ 'title' => __( 'User', 'ultraguard-security-suite' ) ],
                            'routes'     => [ 'title' => __( 'Allowed Routes', 'ultraguard-security-suite' ) ],
                            'rate_limit' => [ 'title' => __( 'Rate Limit', 'ultraguard-security-suite' ) ],
                            'status'     => [ 'title' => __( 'Status', 'ultraguard-security-suite' ) ],
                            'last_used'  => [ 'title' => __( 'Last Used', 'ultraguard-security-suite' ) ],
                            'actions'    => [ 'title' => __( 'Actions', 'ultraguard-security-suite' ) ],
                        ],
                        'data'       => $this->build_key_rows( $rows, $nonce ),
                        'searchable' => true,
                        'pagination' => [ 'enabled' => true, 'page_size' => 25 ],
                    ],
                ],
            ],
            [
                'type'  => 'card',
                'title' => __( 'Request Log', 'ultraguard-security-suite' ),
                'icon'  => 'dashicons-list-view',
                'data'  => [
                    [
                        'type'       => 'data-table',
                        'id'         => 'api-security-log-table',
                        'columns'    => [
                            'endpoint'      => [ 'title' => __( 'Endpoint', 'ultraguard-security-suite' ) ],
                            'method'        => [ 'title' => __( 'Method', 'ultraguard-security-suite' ) ],
                            'auth_type'     => [ 'title' => __( 'Auth Type', 'ultraguard-security-suite' ) ],
                            'ip_address'    => [ 'title' => __( 'IP', 'ultraguard-security-suite' ) ],
                            'response_code' => [ 'title' => __( 'Response', 'ultraguard-security-suite' ) ],
                            'blocked'       => [ 'title' => __( 'Blocked', 'ultraguard-security-suite' ) ],
                            'time'          => [ 'title' => __( 'Time', 'ultraguard-security-suite' ) ],
                        ],
                        'data'       => $this->build_log_rows( $logs ),
                        'searchable' => true,
                        'pagination' => [ 'enabled' => true, 'page_size' => 25 ],
                    ],
                ],
            ],
        ];

        return [
            'type'      => 'page',
            'id'        => 'api-security-dashboard',
            'page_slug' => 'api-security',
            'header'    => [
                'title'    => __( 'REST API & XML-RPC Security', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Control route access, issue managed API keys, and monitor the API surface as a protected part of your WordPress stack.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'api-security-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Refresh Stats', 'ultraguard-security-suite' ), 'ultraguard_api_get_stats', [], 'secondary', 'dashicons-update' ),
                    $this->create_ajax_button( __( 'Clear Log', 'ultraguard-security-suite' ), 'ultraguard_api_clear_log', [], 'danger', 'dashicons-trash', __( 'Clear the API request log?', 'ultraguard-security-suite' ) ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'api_security', __( 'REST API & XML-RPC Security', 'ultraguard-security-suite' ), array_values( array_filter( $data ) ) ),
            'form'      => [ 'enable' => false ],
        ];
    }

    private function build_key_rows( array $rows, string $nonce ): array {
        $data = [];

        foreach ( $rows as $row ) {
            $user = ! empty( $row['user_id'] ) ? get_user_by( 'id', (int) $row['user_id'] ) : false;
            $data[] = [
                'id'         => 'api-key-' . (int) $row['id'],
                'key_name'   => esc_html( (string) ( $row['key_name'] ?? '' ) ),
                'prefix'     => esc_html( (string) ( $row['key_prefix'] ?? '' ) . '...' ),
                'user'       => esc_html( $user ? (string) $user->user_login : __( 'System', 'ultraguard-security-suite' ) ),
                'routes'     => esc_html( ! empty( $row['allowed_routes'] ) ? (string) $row['allowed_routes'] : __( 'All routes', 'ultraguard-security-suite' ) ),
                'rate_limit' => (int) ( $row['rate_limit'] ?? 0 ),
                'status'     => [
                    'content' => ! empty( $row['is_active'] ) ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Revoked', 'ultraguard-security-suite' ),
                    'class'   => ! empty( $row['is_active'] ) ? 'success' : 'secondary',
                ],
                'last_used'  => esc_html( ! empty( $row['last_used_at'] ) ? $this->format_date_time( (string) $row['last_used_at'] ) : __( 'Never', 'ultraguard-security-suite' ) ),
                'actions'    => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Revoke', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_api_revoke_key', 'nonce' => $nonce, 'data' => [ 'id' => (int) $row['id'] ] ] ],
                ] ),
            ];
        }

        return $data;
    }

    private function build_log_rows( array $rows ): array {
        $data = [];
        foreach ( $rows as $index => $row ) {
            $data[] = [
                'id'            => 'api-log-' . $index,
                'endpoint'      => esc_html( (string) ( $row['endpoint'] ?? '' ) ),
                'method'        => esc_html( strtoupper( (string) ( $row['method'] ?? '' ) ) ),
                'auth_type'     => esc_html( (string) ( $row['auth_type'] ?? 'none' ) ),
                'ip_address'    => esc_html( (string) ( $row['ip_address'] ?? '' ) ),
                'response_code' => (int) ( $row['response_code'] ?? 0 ),
                'blocked'       => [
                    'content' => ! empty( $row['was_blocked'] ) ? __( 'Blocked', 'ultraguard-security-suite' ) : __( 'Allowed', 'ultraguard-security-suite' ),
                    'class'   => ! empty( $row['was_blocked'] ) ? 'danger' : 'success',
                ],
                'time'          => esc_html( $this->format_date_time( (string) ( $row['created_at'] ?? '' ) ) ),
            ];
        }

        return $data;
    }

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

        return $this->engine;
    }

    private function preview_key_records(): array {
        return [
            [
                'id'             => 101,
                'key_name'       => 'Headless Storefront',
                'key_prefix'     => 'ug_live_ab12',
                'user_id'        => 1,
                'allowed_routes' => '/wc/v3/orders, /wc/v3/products',
                'rate_limit'     => 120,
                'is_active'      => 1,
                'last_used_at'   => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 2 ),
            ],
            [
                'id'             => 102,
                'key_name'       => 'CRM Sync Worker',
                'key_prefix'     => 'ug_live_cd34',
                'user_id'        => 1,
                'allowed_routes' => '/wp/v2/users/me, /wp/v2/posts',
                'rate_limit'     => 60,
                'is_active'      => 1,
                'last_used_at'   => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 9 ),
            ],
        ];
    }

    private function preview_log_records(): array {
        return [
            [
                'endpoint'      => '/wc/v3/orders',
                'method'        => 'GET',
                'auth_type'     => 'bearer',
                'ip_address'    => '34.210.18.72',
                'response_code' => 200,
                'was_blocked'   => 0,
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - 300 ),
            ],
            [
                'endpoint'      => '/wp/v2/users',
                'method'        => 'POST',
                'auth_type'     => 'none',
                'ip_address'    => '185.143.223.41',
                'response_code' => 403,
                'was_blocked'   => 1,
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - 1200 ),
            ],
            [
                'endpoint'      => 'wp.getUsersBlogs',
                'method'        => 'POST',
                'auth_type'     => 'xmlrpc',
                'ip_address'    => '103.87.212.9',
                'response_code' => 403,
                'was_blocked'   => 1,
                'created_at'    => gmdate( 'Y-m-d H:i:s', time() - 3900 ),
            ],
        ];
    }
}
