<?php
/**
 * PasskeysDashboard - Overview page for the Passkeys module.
 *
 * Shows the current user's enrollment status, registered passkeys table,
 * and recovery-code count. Action buttons trigger AJAX flows (register,
 * delete credential, generate recovery codes). No settings form here —
 * that lives in PasskeysSettings.
 *
 * @package UltraguardPro\modules\authenticator\pages
 */

namespace UltraguardPro\modules\authenticator\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
use UltraguardPro\modules\authenticator\PasskeyManager;
use UltraguardPro\support\LicenseInfo;

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

class PasskeysDashboard extends BasePage {

    /** @var PasskeyManager|null */
    private ?PasskeyManager $passkey_manager = null;

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

    /** Lazy accessor — avoids constructing manager before schema is registered. */
    private function manager(): PasskeyManager {
        if ( $this->passkey_manager === null ) {
            $this->passkey_manager = new PasskeyManager( $this->plugin );
        }
        return $this->passkey_manager;
    }

    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 ) {
            $is_enrolled  = true;
            $credentials  = $this->preview_credentials();
            $unused_count = 8;
        } else {
            $user_id      = get_current_user_id();
            $is_enrolled  = $this->manager()->is_enrolled( $user_id );
            $credentials  = $this->manager()->list_credentials( $user_id );
            $unused_count = $this->manager()->get_unused_recovery_code_count( $user_id );
        }

        // Build rows in the keyed format the render engine expects,
        // matching the pattern used by antivirus quarantine, audit log, etc.
        $rows = array_map( function( $cred ) use ( $nonce ) {
            $id = (int) ( $cred['id'] ?? 0 );
            return [
                'id'          => 'ug-row-' . $id,
                'device_name' => esc_html( $cred['device_name'] ?? __( 'Unknown Device', 'ultraguard-security-suite' ) ),
                'aaguid'      => esc_html( $cred['aaguid'] ?? '—' ),
                'last_used'   => esc_html(
                    ! empty( $cred['last_used'] )
                        ? $this->format_date_time( $cred['last_used'] )
                        : __( 'Never', 'ultraguard-security-suite' )
                ),
                'created_at'  => esc_html( $this->format_date_time( $cred['created_at'] ?? '' ) ),
                'actions'     => $this->credential_actions( $id, $nonce ),
            ];
        }, $credentials );

        return [
            'type'      => 'page',
            'id'        => 'passkeys-dashboard',
            'page_slug' => 'passkeys',
            'header'    => [
                'title'    => __( 'Passkeys', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Passwordless authentication using FIDO2 / WebAuthn security keys and biometrics.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-fingerprint',
                'badge'    => [
                    'text'       => $is_enrolled ? __( 'Enrolled', 'ultraguard-security-suite' ) : __( 'Not Enrolled', 'ultraguard-security-suite' ),
                    'badge_type' => $is_enrolled ? 'success' : 'warning',
                ],
                'actions'  => [
                    [
                        'type'         => 'button',
                        'text'         => __( 'Register New Passkey', 'ultraguard-security-suite' ),
                        'icon'         => 'dashicons-plus-alt',
                        'button_style' => 'primary',
                        'ajax'         => [
                            'action' => 'ultraguard_passkeys_registration_options',
                            'nonce'  => $nonce,
                            'data'   => [],
                        ],
                    ],
                ],
            ],

            'data' => $this->prepend_soft_gated_module_notice( 'authenticator', __( 'Passkeys', 'ultraguard-security-suite' ), array_values( array_filter( [
                $preview_mode ? $this->soft_gated_preview_data_notice(
                    __( 'Passkeys', 'ultraguard-security-suite' ),
                    __( 'These passkeys and recovery-code counts are sample records showing a completed passwordless rollout. Upgrade to register real devices and enable live login protection.', 'ultraguard-security-suite' )
                ) : [],

                // ── Enrollment status stat cards ─────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [
                            'span'      => 4,
                            'component' => [
                                'type'     => 'stat-card',
                                'title'    => __( 'Passkeys Enrolled', 'ultraguard-security-suite' ),
                                'value'    => count( $credentials ),
                                'format'   => 'number',
                                'icon'     => 'dashicons-fingerprint',
                                'class'    => $is_enrolled ? 'success' : 'warning',
                                'animated' => true,
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'     => 'stat-card',
                                'title'    => __( 'Recovery Codes', 'ultraguard-security-suite' ),
                                'value'    => $unused_count,
                                'format'   => 'number',
                                'icon'     => 'dashicons-backup',
                                'class'    => $unused_count > 0 ? 'info' : 'warning',
                                'animated' => false,
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'     => 'stat-card',
                                'title'    => __( 'Status', 'ultraguard-security-suite' ),
                                'value'    => $is_enrolled
                                    ? __( 'Protected', 'ultraguard-security-suite' )
                                    : __( 'Not enrolled', 'ultraguard-security-suite' ),
                                'format'   => 'text',
                                'icon'     => $is_enrolled ? 'dashicons-lock' : 'dashicons-unlock',
                                'class'    => $is_enrolled ? 'success' : 'warning',
                                'animated' => false,
                            ],
                        ],
                    ],
                ],

                // ── Registered passkeys table ────────────────────────────────
                [
                    'type'  => 'card',
                    'title' => __( 'Your Passkeys', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-fingerprint',
                    'data'  => [ [
                        'type'       => 'data-table',
                        'id'         => 'passkeys-credentials-table',
                        'columns'    => [
                            'device_name' => [ 'title' => __( 'Device',     'ultraguard-security-suite' ), 'sortable' => true ],
                            'aaguid'      => [ 'title' => __( 'AAGUID',     'ultraguard-security-suite' ) ],
                            'last_used'   => [ 'title' => __( 'Last Used',  'ultraguard-security-suite' ), 'sortable' => true ],
                            'created_at'  => [ 'title' => __( 'Registered', 'ultraguard-security-suite' ), 'sortable' => true ],
                            'actions'     => [ 'title' => __( 'Actions',    'ultraguard-security-suite' ), 'width' => '100px' ],
                        ],
                        'data'        => $rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $rows ) > 10, 'page_size' => 10 ],
                        'empty_state' => [
                            'title'       => __( 'No passkeys registered yet', 'ultraguard-security-suite' ),
                            'description' => __( 'Click "Register New Passkey" above to add your first passkey.', 'ultraguard-security-suite' ),
                        ],
                    ] ],
                ],

                // ── Recovery codes ───────────────────────────────────────────
                [
                    'type'  => 'card',
                    'title' => __( 'Recovery Codes', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-backup',
                    'data'  => [ [
                        'type'    => 'grid',
                        'columns' => 12,
                        'gap'     => '16px',
                        'items'   => [
                            [
                                'span'      => 8,
                                'component' => [
                                    'type'    => 'paragraph',
                                    'content' => __( 'Recovery codes let you access your account if you lose your passkey device. Each code can only be used once. Store them somewhere safe.', 'ultraguard-security-suite' ),
                                    'class'   => 'description',
                                ],
                            ],
                            [
                                'span'      => 4,
                                'component' => [
                                    'type'         => 'button',
                                    'text'         => __( 'Generate New Codes', 'ultraguard-security-suite' ),
                                    'icon'         => 'dashicons-update',
                                    'button_style' => 'secondary',
                                    'ajax'         => [
                                        'action'  => 'ultraguard_passkeys_generate_recovery_codes',
                                        'nonce'   => $nonce,
                                        'data'    => [],
                                        'confirm' => __( 'This will invalidate all existing recovery codes. Continue?', 'ultraguard-security-suite' ),
                                    ],
                                ],
                            ],
                        ],
                    ] ],
                ],

            ] ) ) ),

            'form' => [ 'enable' => false ],
        ];
    }

    // ── Row-level credential actions ──────────────────────────────────────────

    private function credential_actions( int $id, string $nonce ): array {
        return $this->row_actions( [
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Remove passkey', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_passkeys_delete_credential',
                    'nonce'   => $nonce,
                    'data'    => [ 'credential_id' => $id ],
                    'confirm' => __( 'Remove this passkey? You will need to register it again.', 'ultraguard-security-suite' ),
                ],
            ],
        ] );
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    protected function format_date_time( string $utc_date ): string {
        if ( empty( $utc_date ) ) { return '—'; }
        return get_date_from_gmt(
            $utc_date,
            get_option( 'date_format' ) . ' ' . get_option( 'time_format' )
        );
    }

    private function preview_credentials(): array {
        return [
            [
                'id'          => 21,
                'device_name' => 'MacBook Pro Touch ID',
                'aaguid'      => 'adce0002-35bc-c60a-648b-0b25f1f05503',
                'last_used'   => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS ),
                'created_at'  => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 8 ),
            ],
            [
                'id'          => 22,
                'device_name' => 'YubiKey 5 NFC',
                'aaguid'      => 'fa2b99dc-9e39-4257-8f92-4a30d23c4118',
                'last_used'   => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 4 ),
                'created_at'  => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 19 ),
            ],
        ];
    }
}
