<?php

namespace UltraguardPro\modules\authenticator\pages;

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

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

class TwoFactorDashboard extends BasePage {

    private ?TwoFactorEngine $engine = null;

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

    public function get_scheme( $context ): array {
        $nonce      = $this->create_nonce( 'ultraguard_admin_nonce' );
        $preview_mode = $this->is_soft_gated_module_preview( 'authenticator' );

        if ( $preview_mode ) {
            $enabled      = 18;
            $enforced     = 9;
            $blocked      = 6;
            $users_rows   = $this->preview_users_rows( $nonce );
            $chart        = $this->preview_chart();
            $has_passkeys = true;
        } else {
            $table         = $this->plugin->modules->get_db_tables()->get_table( 'totp_credentials' );
            $enabled       = $table && method_exists( $table, 'count_enabled_users' ) ? (int) $table->count_enabled_users() : 0;
            $enforced      = $table && method_exists( $table, 'count_enforced_users' ) ? (int) $table->count_enforced_users() : 0;
            $blocked       = $this->engine()->count_blocked_today();
            $users_rows    = $this->build_users_rows( $table ? $table->get_by( [], 250, 'updated_at', 'DESC' ) : [], $nonce );
            $chart         = $this->engine()->get_metrics( 30 );
            $authenticator = $this->plugin->modules->get( 'authenticator' );
            $has_passkeys  = $authenticator && method_exists( $authenticator, 'is_passkeys_available' ) ? (bool) $authenticator->is_passkeys_available() : false;
        }

        $data = [
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'Authenticator', 'ultraguard-security-suite' ),
                __( 'The enrollment counts, verification trend, and user readiness list below are sample records that show how a protected team rollout looks. Upgrade to activate live 2FA and Passkeys for your users.', 'ultraguard-security-suite' )
            ) : [],
        ];

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-two-factor-dashboard',
            'page_slug' => 'two-factor',
            'header'    => [
                'title'    => __( 'Authenticator', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Manage sign-in protection across authenticator apps, backup codes, and passkeys from one place.', 'ultraguard-security-suite' ),
                'actions'  => [
                    [
                        'type'         => 'button',
                        'text'         => __( 'Start My Setup', 'ultraguard-security-suite' ),
                        'button_style' => 'primary',
                        'icon'         => 'dashicons-smartphone',
                        'data'         => [ 'ug-2fa-setup' => '1' ],
                    ],
                    $has_passkeys ? $this->create_url_button( __( 'Open Passkeys', 'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=passkeys' ), 'secondary', 'dashicons-fingerprint' ) : null,
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'two-factor-settings' ), 'secondary', 'dashicons-admin-settings' ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'authenticator', __( 'Authenticator', 'ultraguard-security-suite' ), array_merge( array_values( array_filter( $data ) ), [
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Users Enabled', 'ultraguard-security-suite' ), 'value' => $enabled, 'format' => 'number', 'icon' => 'dashicons-shield-alt', 'class' => 'success' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Users Enforced', 'ultraguard-security-suite' ), 'value' => $enforced, 'format' => 'number', 'icon' => 'dashicons-admin-users', 'class' => 'info' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked Today', 'ultraguard-security-suite' ), 'value' => $blocked, 'format' => 'number', 'icon' => 'dashicons-lock', 'class' => $blocked > 0 ? 'warning' : 'success' ] ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Authentication Options', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-shield-alt',
                    'data'  => [
                        [
                            'type'    => 'paragraph',
                            'content' => __( 'Authenticator supports both app-based verification codes and Passkeys. Use authenticator apps for broad device compatibility, or enable Passkeys for faster passwordless sign-in with biometrics and security keys.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'type'    => 'paragraph',
                            'content' => $has_passkeys
                                ? __( 'Passkeys are available on this site. You can register a passkey to sign in with Face ID, Touch ID, Windows Hello, or a hardware security key.', 'ultraguard-security-suite' )
                                : __( 'Passkeys are available in UltraGuard Pro and let users sign in with Face ID, Touch ID, Windows Hello, or a hardware security key.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'type'      => 'button-group',
                            'alignment' => 'left',
                            'buttons'   => [
                                [
                                    'type'         => 'button',
                                    'text'         => $has_passkeys ? __( 'Open Passkeys', 'ultraguard-security-suite' ) : __( 'Upgrade For Passkeys', 'ultraguard-security-suite' ),
                                    'button_style' => 'primary',
                                    'icon'         => 'dashicons-fingerprint',
                                    'url'          => $has_passkeys
                                        ? admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=passkeys' )
                                        : admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=upgrade' ),
                                ],
                                [
                                    'type'         => 'button',
                                    'text'         => __( 'Open Two-Factor Settings', 'ultraguard-security-suite' ),
                                    'button_style' => 'secondary',
                                    'icon'         => 'dashicons-admin-settings',
                                    'url'          => $this->get_page_url( 'two-factor-settings' ),
                                ],
                            ],
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Setup Wizard', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-smartphone',
                    'data'  => [
                        [
                            'type'    => 'paragraph',
                            'content' => __( 'Generate a QR code, verify your first TOTP code, and safely store your recovery codes.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'type'    => 'paragraph',
                            'content' => __( 'When setup opens, scan the QR code in your authenticator app, then enter the current 6-digit code from that app to finish activation.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'type'    => 'html',
                            'content' => '<div id="ug-two-factor-setup-target"></div>',
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Bulk Enforcement', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-users',
                    'data'  => [
                        [
                            'type'        => 'select',
                            'name'        => 'two_factor_bulk_role',
                            'label'       => __( 'Require 2FA for role', 'ultraguard-security-suite' ),
                            'description' => __( 'Use the settings page to persist role enforcement. This control reflects the available roles on the site.', 'ultraguard-security-suite' ),
                            'options'     => array_values( array_map(
                                static function ( $label, $slug ) {
                                    return [ 'value' => $slug, 'label' => translate_user_role( $label ) ];
                                },
                                wp_roles()->get_names(),
                                array_keys( wp_roles()->get_names() )
                            ) ),
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Verification Activity', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-chart-line',
                    'data'  => [
                        [
                            'type'       => 'chart',
                            'chart_type' => 'line',
                            'height'     => '260px',
                            'labels'     => $chart['labels'],
                            'datasets'   => [
                                [ 'label' => __( 'Success', 'ultraguard-security-suite' ), 'data' => $chart['success'], 'borderColor' => '#1d7f49', 'backgroundColor' => 'rgba(29,127,73,0.12)', 'fill' => true, 'tension' => 0.35 ],
                                [ 'label' => __( 'Failure', 'ultraguard-security-suite' ), 'data' => $chart['failure'], 'borderColor' => '#b42318', 'backgroundColor' => 'rgba(180,35,24,0.10)', 'fill' => true, 'tension' => 0.35 ],
                            ],
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Users and 2FA Status', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-groups',
                    'data'  => [
                        [
                            'type'       => 'data-table',
                            'id'         => 'two-factor-users-table',
                            'columns'    => [
                                'user'      => [ 'title' => __( 'User', 'ultraguard-security-suite' ), 'sortable' => true ],
                                'role'      => [ 'title' => __( 'Role', 'ultraguard-security-suite' ) ],
                                'status'    => [ 'title' => __( '2FA Status', 'ultraguard-security-suite' ) ],
                                'last_used' => [ 'title' => __( 'Last Used', 'ultraguard-security-suite' ), 'sortable' => true ],
                                'actions'   => [ 'title' => __( 'Actions', 'ultraguard-security-suite' ) ],
                            ],
                            'data'       => $users_rows,
                            'searchable' => true,
                            'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
                        ],
                    ],
                ],
            ] ) ),
            'form'      => [ 'enable' => false ],
            'nonce'     => $nonce,
        ];
    }

    private function build_users_rows( array $credentials, string $nonce ): array {
        $rows = [];
        $map  = [];

        foreach ( $credentials as $row ) {
            $map[ (int) $row['user_id'] ] = $row;
        }

        foreach ( get_users( [ 'number' => 250, 'orderby' => 'display_name', 'order' => 'ASC' ] ) as $user ) {
            $cred   = $map[ (int) $user->ID ] ?? [];
            $status = ! empty( $cred['is_enabled'] ) ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' );

            $rows[] = [
                'id'       => 'ug-2fa-user-' . (int) $user->ID,
                'user'     => esc_html( $user->display_name ),
                'role'     => esc_html( implode( ', ', array_map( 'translate_user_role', (array) $user->roles ) ) ),
                'status'   => [ 'content' => $status, 'class' => ! empty( $cred['is_enabled'] ) ? 'success' : 'secondary' ],
                'last_used'=> ! empty( $cred['last_used_at'] ) ? esc_html( $this->format_date_time( $cred['last_used_at'] ) ) : __( 'Never', 'ultraguard-security-suite' ),
                'actions'  => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Prompt Setup', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'url' => admin_url( 'user-edit.php?user_id=' . (int) $user->ID . '#ultraguard_two_factor_enabled' ) ],
                    [ 'type' => 'button', 'text' => __( 'Disable', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_2fa_disable', 'nonce' => $nonce, 'data' => [ 'user_id' => (int) $user->ID ] ] ],
                    [ 'type' => 'button', 'text' => __( 'Reset Backup Codes', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'ajax' => [ 'action' => 'ultraguard_2fa_regenerate_backup', 'nonce' => $nonce, 'data' => [ 'user_id' => (int) $user->ID ] ] ],
                ] ),
            ];
        }

        return $rows;
    }

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

        return $this->engine;
    }

    private function preview_users_rows( string $nonce ): array {
        return [
            [
                'id'       => 'ug-2fa-user-21',
                'user'     => 'Store Admin',
                'role'     => 'Administrator',
                'status'   => [ 'content' => __( 'Enabled', 'ultraguard-security-suite' ), 'class' => 'success' ],
                'last_used'=> __( 'Today 10:18 am', 'ultraguard-security-suite' ),
                'actions'  => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Prompt Setup', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'url' => self_admin_url( 'user-edit.php?user_id=21#ultraguard_two_factor_enabled' ) ],
                    [ 'type' => 'button', 'text' => __( 'Disable', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_2fa_disable', 'nonce' => $nonce, 'data' => [ 'user_id' => 21 ] ] ],
                    [ 'type' => 'button', 'text' => __( 'Reset Backup Codes', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'ajax' => [ 'action' => 'ultraguard_2fa_regenerate_backup', 'nonce' => $nonce, 'data' => [ 'user_id' => 21 ] ] ],
                ] ),
            ],
            [
                'id'       => 'ug-2fa-user-22',
                'user'     => 'Support Manager',
                'role'     => 'Shop Manager',
                'status'   => [ 'content' => __( 'Enabled', 'ultraguard-security-suite' ), 'class' => 'success' ],
                'last_used'=> __( 'Yesterday 6:42 pm', 'ultraguard-security-suite' ),
                'actions'  => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Prompt Setup', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'url' => self_admin_url( 'user-edit.php?user_id=22#ultraguard_two_factor_enabled' ) ],
                    [ 'type' => 'button', 'text' => __( 'Disable', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_2fa_disable', 'nonce' => $nonce, 'data' => [ 'user_id' => 22 ] ] ],
                    [ 'type' => 'button', 'text' => __( 'Reset Backup Codes', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'ajax' => [ 'action' => 'ultraguard_2fa_regenerate_backup', 'nonce' => $nonce, 'data' => [ 'user_id' => 22 ] ] ],
                ] ),
            ],
            [
                'id'       => 'ug-2fa-user-23',
                'user'     => 'Content Editor',
                'role'     => 'Editor',
                'status'   => [ 'content' => __( 'Disabled', 'ultraguard-security-suite' ), 'class' => 'secondary' ],
                'last_used'=> __( 'Never', 'ultraguard-security-suite' ),
                'actions'  => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Prompt Setup', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'url' => self_admin_url( 'user-edit.php?user_id=23#ultraguard_two_factor_enabled' ) ],
                    [ 'type' => 'button', 'text' => __( 'Disable', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_2fa_disable', 'nonce' => $nonce, 'data' => [ 'user_id' => 23 ] ] ],
                    [ 'type' => 'button', 'text' => __( 'Reset Backup Codes', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'ajax' => [ 'action' => 'ultraguard_2fa_regenerate_backup', 'nonce' => $nonce, 'data' => [ 'user_id' => 23 ] ] ],
                ] ),
            ],
        ];
    }

    private function preview_chart(): array {
        return [
            'labels'  => [ 'Week 1', 'Week 2', 'Week 3', 'Week 4' ],
            'success' => [ 12, 17, 19, 23 ],
            'failure' => [ 4, 3, 5, 2 ],
        ];
    }
}



