<?php

namespace UltraguardPro\modules\loginlimiter\pages;

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

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

class LoginProtectDashboard extends BasePage {

    private ?LoginUrlEngine $engine = null;

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

    public function get_scheme( $context ): array {
        $engine     = $this->engine();
        $stats      = $engine->get_stats();
        $secret     = $engine->get_secret_path();
        $custom_set = 'wp-login.php' !== $secret;
        $login_url  = $custom_set ? home_url( '/' . trim( $secret, '/' ) . '/' ) : wp_login_url();

        return [
            'type'      => 'page',
            'id'        => 'login-protect-dashboard',
            'page_slug' => 'login-protect',
            'header'    => [
                'title'    => __( 'Login URL Protection', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Hide wp-login.php behind a secret path and monitor direct hits to the old endpoint.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'login-limiter-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Generate New Path', 'ultraguard-security-suite' ), 'ultraguard_login_protect_generate_path', [], 'primary', 'dashicons-randomize', __( 'Generating a new path will break old bookmarks until you save it in settings.', 'ultraguard-security-suite' ) ),
                ],
            ],
            'data'      => [
                ! $custom_set
                    ? [ 'type' => 'alert-box', 'alert_type' => 'warning', 'title' => __( 'Custom path not set', 'ultraguard-security-suite' ), 'message' => __( 'Set a custom login path to start hiding wp-login.php.', 'ultraguard-security-suite' ) ]
                    : [ 'type' => 'card', 'title' => __( 'Current Login URL', 'ultraguard-security-suite' ), 'icon' => 'dashicons-admin-links', 'data' => [
                        [ 'type' => 'text', 'name' => 'login-protect-current-url', 'label' => __( 'Secret login URL', 'ultraguard-security-suite' ), 'value' => $login_url, 'attributes' => [ 'data-copy-source' => 'login-protect-url' ] ],
                        [ 'type' => 'button', 'text' => __( 'Copy URL', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'attributes' => [ 'data-copy-login-url' => '1' ] ],
                    ] ],
                [ 'type' => 'grid', 'columns' => 12, 'gap' => '16px', 'items' => [
                    [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked Today', 'ultraguard-security-suite' ), 'value' => $stats['today'], 'format' => 'number', 'icon' => 'dashicons-lock', 'class' => $stats['today'] > 0 ? 'warning' : 'success' ] ],
                    [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked This Week', 'ultraguard-security-suite' ), 'value' => $stats['week'], 'format' => 'number', 'icon' => 'dashicons-calendar-alt', 'class' => 'info' ] ],
                    [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Unique IPs', 'ultraguard-security-suite' ), 'value' => $stats['unique_ips'], 'format' => 'number', 'icon' => 'dashicons-networking', 'class' => 'info' ] ],
                ] ],
                [ 'type' => 'card', 'title' => __( 'Blocked Attempts per Day', 'ultraguard-security-suite' ), 'icon' => 'dashicons-chart-bar', 'data' => [ [ 'type' => 'chart', 'chart_type' => 'bar', 'height' => '250px', 'labels' => array_map( static fn( $row ) => (string) $row['day'], $stats['chart'] ), 'datasets' => [ [ 'label' => __( 'Attempts', 'ultraguard-security-suite' ), 'data' => array_map( static fn( $row ) => (int) $row['total'], $stats['chart'] ), 'backgroundColor' => '#b42318' ] ] ] ] ],
                [ 'type' => 'card', 'title' => __( 'Recent Blocked Attempts', 'ultraguard-security-suite' ), 'icon' => 'dashicons-list-view', 'data' => [ [
                    'type'       => 'data-table',
                    'id'         => 'login-protect-attempts-table',
                    'columns'    => [
                        'ip'      => [ 'title' => __( 'IP', 'ultraguard-security-suite' ) ],
                        'url'     => [ 'title' => __( 'Attempted URL', 'ultraguard-security-suite' ) ],
                        'country' => [ 'title' => __( 'Country', 'ultraguard-security-suite' ) ],
                        'time'    => [ 'title' => __( 'Time', 'ultraguard-security-suite' ) ],
                    ],
                    'data'       => $this->build_rows( $stats['recent'] ),
                    'searchable' => true,
                    'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
                ] ] ],
            ],
            'form'      => [ 'enable' => false ],
        ];
    }

    private function build_rows( array $rows ): array {
        $data = [];
        foreach ( $rows as $row ) {
            $data[] = [
                'id'      => 'lp-row-' . (int) ( $row['id'] ?? 0 ),
                'ip'      => esc_html( (string) ( $row['ip_address'] ?? '' ) ),
                'url'     => esc_html( mb_strimwidth( (string) ( $row['attempted_url'] ?? '' ), 0, 70, '...' ) ),
                'country' => esc_html( (string) ( $row['country_code'] ?? '' ) ),
                'time'    => esc_html( ! empty( $row['created_at'] ) ? $this->format_date_time( $row['created_at'] ) : '' ),
            ];
        }

        return $data;
    }

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

        return $this->engine;
    }
}
