<?php
/**
 * Admin Class
 * 
 * Handles admin panel functionality and settings
 * 
 * @package MDLOGIN_Passkey
 * @since 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * MDLOGIN_Passkey_Admin class
 * 
 * @since 1.0.0
 */
class MDLOGIN_Passkey_Admin {

    /**
     * Instance of this class
     *
     * @var MDLOGIN_Passkey_Admin
     */
    private static $instance = null;

    /**
     * Get instance of this class
     *
     * @return MDLOGIN_Passkey_Admin
     */
    public static function mdlogin_get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        $this->mdlogin_init_hooks();
    }

    /**
     * Initialize hooks
     */
    private function mdlogin_init_hooks() {
        // Add admin menu
        add_action('admin_menu', array($this, 'mdlogin_add_admin_menu'));
        add_action('admin_head', array($this, 'mdlogin_admin_menu_icon_styles'));
        
        // Add admin scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'mdlogin_enqueue_admin_scripts'));
        add_action( 'admin_enqueue_scripts', array( $this, 'mdlogin_enqueue_admin_styles' ) );

        // Register settings
        add_action('admin_init', array($this, 'mdlogin_register_settings'));
        
        // Add settings link to plugins page
        add_filter('plugin_action_links_' . MDLOGIN_PASSKEY_PLUGIN_BASENAME, array($this, 'mdlogin_add_settings_link'));
        
        // AJAX handlers for admin actions
        add_action('wp_ajax_mdlogin_passkey_get_user_credentials', array($this, 'mdlogin_ajax_get_user_credentials'));
        add_action('wp_ajax_mdlogin_passkey_delete_credential', array($this, 'mdlogin_ajax_delete_credential'));
        add_action('wp_ajax_mdlogin_passkey_delete_all_credentials', array($this, 'mdlogin_ajax_delete_all_credentials'));
    }

    /**
     * Add admin menu
     */
    public function mdlogin_add_admin_menu() {
        add_menu_page(
            __('Passkey Settings', 'multidots-passkey-login'), 
            __('Multipasskey', 'multidots-passkey-login'),
            'manage_options',
            'mdlogin-settings',
            array($this, 'mdlogin_settings_page'),
            MDLOGIN_PASSKEY_PLUGIN_URL . 'assets/images/Multipasskey-new.svg',
            25
        );

        // Override the auto-created submenu item (to change label from "Passkey" to "Setting")
        add_submenu_page(
            'mdlogin-settings',
            __('Passkey Settings', 'multidots-passkey-login'),
            __('Settings', 'multidots-passkey-login'), // This changes the submenu label
            'manage_options',
            'mdlogin-settings', // same slug as parent
            array($this, 'mdlogin_settings_page')
        );

        add_submenu_page(
            'mdlogin-settings',
            __('Passkey Management', 'multidots-passkey-login'),
            __('Passkeys', 'multidots-passkey-login'),
            'manage_options',
            'mdlogin-management',
            array($this, 'mdlogin_admin_page')
        );
    }

    /**
     * Admin menu icon styles.
     */
    public function mdlogin_admin_menu_icon_styles() {
        ?>
        <style>
            #adminmenu .toplevel_page_mdlogin-settings .wp-menu-image img {
                width: 20px;
                height: 20px;
                padding: 7px 0 0;
                opacity: 0.6;
            }

            #adminmenu .toplevel_page_mdlogin-settings:hover .wp-menu-image img,
            #adminmenu .toplevel_page_mdlogin-settings.wp-has-current-submenu .wp-menu-image img,
            #adminmenu .toplevel_page_mdlogin-settings.current .wp-menu-image img {
                opacity: 1;
            }
        </style>
        <?php
    }

    /**
     * Enqueue admin scripts and styles
     *
     * @param string $hook_suffix Current admin page
     */
    public function mdlogin_enqueue_admin_scripts($hook_suffix) {
        if ( 'mdlogin-settings_page_mdlogin-management' !== $hook_suffix ) {
            return;
        }

        wp_enqueue_script(
            'mdlogin-admin',
            MDLOGIN_PASSKEY_PLUGIN_URL . 'assets/js/mdlogin-admin.js',
            array('jquery'),
            MDLOGIN_PASSKEY_VERSION,
            true
        );

        wp_localize_script('mdlogin-admin', 'mdPasskeyAdmin', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('mdlogin_passkey_admin_nonce'),
            'strings' => array(
                'confirmDelete' => __('Are you sure you want to delete this credential?', 'multidots-passkey-login'),
                'deleteSuccess' => __('Credential deleted successfully.', 'multidots-passkey-login'),
                'deleteError' => __('Failed to delete credential.', 'multidots-passkey-login'),
                'loadError' => __('Failed to load credentials.', 'multidots-passkey-login'),
            )
        ));

        wp_enqueue_style(
            'mdlogin-admin',
            MDLOGIN_PASSKEY_PLUGIN_URL . 'assets/css/mdlogin-admin.css',
            array(),
            MDLOGIN_PASSKEY_VERSION
        );
    }

    	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @param string $hook_suffix The current admin page.
	 * @since    1.0
	 */
    public function mdlogin_enqueue_admin_styles( $hook_suffix ) {

        if ( 'toplevel_page_mdlogin-settings' !== $hook_suffix ) {
            return;
        }

        wp_register_style( 'mdlogin-settings-style', MDLOGIN_PASSKEY_PLUGIN_URL . 'assets/css/mdlogin-admin.css', array(), MDLOGIN_PASSKEY_VERSION );
        wp_enqueue_style( 'mdlogin-settings-style' );
    }

    /**
     * Register settings
     */
    public function mdlogin_register_settings() {
        register_setting('mdlogin_passkey_settings', 'mdlogin_passkey_settings', array(
            'sanitize_callback' => array($this, 'mdlogin_sanitize_settings')
        ));

        add_settings_section(
            'mdlogin_passkey_general',
            __('General Settings', 'multidots-passkey-login'),
            array($this, 'mdlogin_settings_section_callback'),
            'mdlogin_passkey_settings'
        );

        add_settings_field(
            'enabled',
            __('Enable Passkey', 'multidots-passkey-login'),
            array($this, 'mdlogin_checkbox_field_callback'),
            'mdlogin_passkey_settings',
            'mdlogin_passkey_general',
            array('field' => 'enabled')
        );

        add_settings_field(
            'require_https',
            __('Require HTTPS', 'multidots-passkey-login'),
            array($this, 'mdlogin_checkbox_field_callback'),
            'mdlogin_passkey_settings',
            'mdlogin_passkey_general',
            array('field' => 'require_https')
        );

        add_settings_field(
            'session_timeout',
            __('Session Timeout (seconds)', 'multidots-passkey-login'),
            array($this, 'mdlogin_number_field_callback'),
            'mdlogin_passkey_settings',
            'mdlogin_passkey_general',
            array('field' => 'session_timeout', 'min' => 60, 'max' => 3600)
        );

        add_settings_field(
            'max_credentials_per_user',
            __('Max Credentials per User', 'multidots-passkey-login'),
            array($this, 'mdlogin_number_field_callback'),
            'mdlogin_passkey_settings',
            'mdlogin_passkey_general',
            array('field' => 'max_credentials_per_user', 'min' => 1, 'max' => 10)
        );
    }

    /**
     * Sanitize settings
     *
     * @param array $input Input data
     * @return array
     */
    public function mdlogin_sanitize_settings($input) {
        $sanitized = array();

        $sanitized['enabled'] = isset($input['enabled']) ? true : false;
        $sanitized['require_https'] = isset($input['require_https']) ? true : false;
        $sanitized['session_timeout'] = absint($input['session_timeout'] ?? 300);
        $sanitized['max_credentials_per_user'] = absint($input['max_credentials_per_user'] ?? 3);


        // Validate ranges
        if ($sanitized['session_timeout'] < 60) {
            $sanitized['session_timeout'] = 60;
        } elseif ($sanitized['session_timeout'] > 3600) {
            $sanitized['session_timeout'] = 3600;
        }

        if ($sanitized['max_credentials_per_user'] < 1) {
            $sanitized['max_credentials_per_user'] = 1;
        } elseif ($sanitized['max_credentials_per_user'] > 10) {
            $sanitized['max_credentials_per_user'] = 10;
        }

        return $sanitized;
    }

    /**
     * Settings section callback
     */
    public function mdlogin_settings_section_callback() {
        echo '<p>' . esc_html__('Configure the Passkey plugin settings.', 'multidots-passkey-login') . '</p>';
    }

    /**
     * Checkbox field callback
     *
     * @param array $args Field arguments
     */
    public function mdlogin_checkbox_field_callback($args) {
        $settings = get_option('mdlogin_passkey_settings', array());
        $field = $args['field'];
        $value = isset($settings[$field]) ? $settings[$field] : false;

        echo '<label class="mdlogin-checkbox-field" for="' . esc_attr($field) . '">';
        echo '<input type="checkbox" class="mdlogin-checkbox-field__input" id="' . esc_attr($field) . '" name="mdlogin_passkey_settings[' . esc_attr($field) . ']" value="1" ' . checked(1, $value, false) . '>';
        echo '<span class="mdlogin-checkbox-field__switch" aria-hidden="true"></span>';
        echo '</label>';
    }

    /**
     * Number field callback
     *
     * @param array $args Field arguments
     */
    public function mdlogin_number_field_callback($args) {
        $settings = get_option('mdlogin_passkey_settings', array());
        $field = $args['field'];
        $value = isset($settings[$field]) ? $settings[$field] : $args['min'] ?? 0;
        $min = $args['min'] ?? 0;
        $max = $args['max'] ?? 999;
        
        echo '<input type="number" id="' . esc_attr($field) . '" name="mdlogin_passkey_settings[' . esc_attr($field) . ']" value="' . esc_attr($value) . '" min="' . esc_attr($min) . '" max="' . esc_attr($max) . '">';
    }

    /**
     * Add settings link to plugins page
     *
     * @param array $links Plugin action links
     * @return array
     */
    public function mdlogin_add_settings_link($links) {
        $settings_link = '<a href="' . admin_url('admin.php?page=mdlogin-settings') . '">' . esc_html__('Settings', 'multidots-passkey-login') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    /**
     * Render the plugin brand header bar.
     */
    private function mdlogin_render_brand_header() {
        ?>
        <div class="cf-dashboard-layout__header">
            <div class="mdlogin-brand">
                <img src="<?php echo esc_url( MDLOGIN_PASSKEY_PLUGIN_URL . 'assets/images/Multipasskey.svg' ); ?>" width="32" height="32" class="mdlogin-brand-icon" alt="<?php esc_attr_e( 'Multipasskey', 'multidots-passkey-login' ); ?>" />
                <span class="mdlogin-brand-title"><?php esc_html_e( 'Multipasskey', 'multidots-passkey-login' ); ?></span>
                <span class="mdlogin-brand-version">v<?php echo esc_html( MDLOGIN_PASSKEY_VERSION ); ?></span>
            </div>
        </div>
        <?php
    }

    /**
     * Render settings page tabs.
     *
     * @param string $active_tab Active tab slug.
     */
    private function mdlogin_render_settings_tabs( $active_tab ) {
        $tabs = array(
            'settings'    => array(
                'label' => __( 'Settings', 'multidots-passkey-login' ),
                'url'   => admin_url( 'admin.php?page=mdlogin-settings&tab=settings' ),
            ),
            'shortcodes'  => array(
                'label' => __( 'Shortcodes', 'multidots-passkey-login' ),
                'url'   => admin_url( 'admin.php?page=mdlogin-settings&tab=shortcodes' ),
            ),
            'system_info' => array(
                'label' => __( 'System Info', 'multidots-passkey-login' ),
                'url'   => admin_url( 'admin.php?page=mdlogin-settings&tab=system_info' ),
            ),
            'about'       => array(
                'label' => __( 'About', 'multidots-passkey-login' ),
                'url'   => admin_url( 'admin.php?page=mdlogin-settings&tab=about' ),
            ),
        );
        ?>
        <div class="cf-dashboard-layout__tabs-list nav-tab-wrapper">
            <?php foreach ( $tabs as $tab_id => $tab ) : ?>
                <a href="<?php echo esc_url( $tab['url'] ); ?>" class="nav-tab <?php echo esc_attr( $active_tab === $tab_id ? 'nav-tab-active' : '' ); ?>">
                    <?php echo esc_html( $tab['label'] ); ?>
                </a>
            <?php endforeach; ?>
        </div>
        <?php
    }

    /**
     * Admin page callback
     */
    public function mdlogin_admin_page() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'multidots-passkey-login'));
        }

        // Load the list table
        require_once MDLOGIN_PASSKEY_PLUGIN_DIR . 'admin/class-mdlogin-passkey-users-list-table.php';
        $list_table = new MDLOGIN_Passkey_Users_List_Table();
        
        // Process bulk actions
        $list_table->process_bulk_action();
        
        $list_table->prepare_items();
        
        ?>
        <div class="wrap mdlogin-management-layout">
            <h1><?php esc_html_e( 'Active Passkey Users', 'multidots-passkey-login' ); ?></h1>

            <div class="mdlogin-table-container">
                <form method="post">
                    <?php
                    $list_table->search_box( __( 'Search', 'multidots-passkey-login' ), 'user-search' );
                    $list_table->display();
                    ?>
                </form>
            </div>

            <!-- Credentials Modal -->
            <div id="mdlogin-modal" class="mdlogin-modal" style="display: none;">
                <div class="mdlogin-modal-content">
                    <span class="mdlogin-modal-close">&times;</span>
                    <h2><?php esc_html_e('User Credentials', 'multidots-passkey-login'); ?></h2>
                    <div id="mdlogin-credentials-list"></div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Settings page callback
     */
    public function mdlogin_settings_page() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'multidots-passkey-login'));
        }
        // Current active tab - validate against allowed values for security.
        $active_tab   = 'settings';
        $allowed_tabs = array( 'settings', 'shortcodes', 'system_info', 'about' );

        $requested_tab = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
        if ( $requested_tab ) {
            $requested_tab = sanitize_text_field( $requested_tab );
        }

        if ( ! empty( $requested_tab ) && in_array( $requested_tab, $allowed_tabs, true ) ) {
            $active_tab = $requested_tab;
        }
        ?>
        <div class="md-admin-dashboard-main-layout">
            <div class="cf-dashboard-layout">
                <?php $this->mdlogin_render_brand_header(); ?>
                <div class="cf-dashboard-layout__outer">
                    <?php $this->mdlogin_render_settings_tabs( $active_tab ); ?>
                    <div class="cf-dashboard-layout__inner">
                        <div class="cf-dashboard-layout__form">
                            <?php if ( 'settings' === $active_tab ) : ?>
                                <form method="post" action="options.php">
                                    <?php
                                    settings_fields( 'mdlogin_passkey_settings' );
                                    do_settings_sections( 'mdlogin_passkey_settings' );
                                    submit_button();
                                    ?>
                                </form>

                            <?php elseif ( 'shortcodes' === $active_tab ) : ?>
                                <div class="mdlogin-shortcodes-section">
                                    <h2><?php esc_html_e( 'Available Shortcodes', 'multidots-passkey-login' ); ?></h2>
                                    <p><?php esc_html_e( 'Use these shortcodes to add passkey functionality to your pages and posts:', 'multidots-passkey-login' ); ?></p>

                                    <?php
                                    $shortcodes = MDLOGIN_Passkey_Shortcodes::mdlogin_get_available_shortcodes();
                                    foreach ( $shortcodes as $key => $shortcode ) :
                                        ?>
                                        <div class="mdlogin-shortcode-item">
                                            <h3><?php echo esc_html( ucfirst( $key ) ); ?> <?php esc_html_e( 'Shortcode', 'multidots-passkey-login' ); ?></h3>
                                            <div class="mdlogin-shortcode-code">
                                                <code><?php echo esc_html( $shortcode['shortcode'] ); ?></code>
                                            </div>
                                            <p><?php echo esc_html( $shortcode['description'] ); ?></p>
                                        </div>
                                    <?php endforeach; ?>
                                </div>

                            <?php elseif ( 'system_info' === $active_tab ) : ?>
                                <div class="mdlogin-settings-info">
                                    <h2><?php esc_html_e( 'System Information', 'multidots-passkey-login' ); ?></h2>
                                    <table class="form-table">
                                        <tr>
                                            <th><?php esc_html_e( 'PHP Version', 'multidots-passkey-login' ); ?></th>
                                            <td><?php echo esc_html( PHP_VERSION ); ?></td>
                                        </tr>
                                        <tr>
                                            <th><?php esc_html_e( 'WordPress Version', 'multidots-passkey-login' ); ?></th>
                                            <td><?php echo esc_html( get_bloginfo( 'version' ) ); ?></td>
                                        </tr>
                                        <tr>
                                            <th><?php esc_html_e( 'HTTPS Enabled', 'multidots-passkey-login' ); ?></th>
                                            <td><?php echo is_ssl() ? '✓' : '✗'; ?></td>
                                        </tr>
                                        <tr>
                                            <th><?php esc_html_e( 'WebAuthn Support', 'multidots-passkey-login' ); ?></th>
                                            <td><?php echo esc_html( $this->mdlogin_check_webauthn_support() ? '✓' : '✗' ); ?></td>
                                        </tr>
                                    </table>
                                </div>

                            <?php elseif ( 'about' === $active_tab ) : ?>
                                <?php $this->mdlogin_render_about_tab(); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render About tab content (same as Multiadmin).
     */
    private function mdlogin_render_about_tab() {
        ?>
        <div class="about-md">
            <figure class="about-md__logo">
                <img src="<?php echo esc_url( MDLOGIN_PASSKEY_PLUGIN_URL . 'assets/images/mdinc-logo.svg' ); ?>" alt="<?php esc_attr_e( 'Multidots', 'multidots-passkey-login' ); ?>">
            </figure>
            <div class="md-info">
                <p><?php esc_html_e( 'Multidots is an enterprise web agency specializing in WordPress since 2009. We help brands build, migrate, and scale complex websites and digital platforms on WordPress and WooCommerce.', 'multidots-passkey-login' ); ?></p>
                <p>
                    <?php
                    echo wp_kses_post(
                        sprintf(
                            /* translators: %1$s: opening strong tag, %2$s: closing strong tag */
                            __( 'As a %1$sWordPress VIP Gold Partner%2$s and one of the %1$stop contributors to WordPress globally%2$s, our team brings enterprise-grade engineering, security, and performance to every build. We\'ve delivered 500+ websites and 300+ platform migrations for organizations that need their web presence to scale.', 'multidots-passkey-login' ),
                            '<strong>',
                            '</strong>'
                        )
                    );
                    ?>
                </p>
                <h3 class="about-md__subheading"><?php esc_html_e( 'Need something custom?', 'multidots-passkey-login' ); ?></h3>
                <p><?php esc_html_e( 'If you\'re looking for a custom plugin, a tailored feature, or a fully custom enterprise solution built for your brand, our team can help. From custom WordPress and WooCommerce development to large-scale platform builds, we partner with you to turn your requirements into reality.', 'multidots-passkey-login' ); ?></p>
                <a href="https://www.multidots.com/contact/" class="contactus-btn button-primary" target="_blank" rel="noreferrer noopener"><?php esc_html_e( 'Talk to Our Experts →', 'multidots-passkey-login' ); ?></a>
            </div>
        </div>
        <?php
    }

    /**
     * Enhanced nonce verification for admin actions
     *
     * @param string $nonce Nonce to verify
     * @param string $action Action name
     * @return bool True if valid, false otherwise
     */
    private function mdlogin_verify_admin_nonce($nonce, $action) {
        if (empty($nonce) || empty($action)) {
            return false;
        }

        // Validate nonce format
        if (!preg_match('/^[a-zA-Z0-9]{10}$/', $nonce)) {
            return false;
        }

        // Verify nonce
        return wp_verify_nonce($nonce, $action);
    }

    /**
     * Enhanced input validation for admin operations
     *
     * @param mixed $input Input to validate
     * @param string $type Type of validation
     * @return mixed|false Sanitized input or false if invalid
     */
    private function mdlogin_validate_admin_input($input, $type) {
        switch ($type) {
            case 'user_id':
                $input = absint($input);
                return $input > 0 ? $input : false;
                
            case 'credential_id':
                $input = sanitize_text_field($input);
                return !empty($input) && strlen($input) >= 10 ? $input : false;
                
            case 'nonce':
                $input = sanitize_text_field($input);
                return !empty($input) && strlen($input) === 10 ? $input : false;
                
            default:
                return sanitize_text_field($input);
        }
    }

    /**
     * AJAX handler for getting user credentials
     */
    public function mdlogin_ajax_get_user_credentials() {
        // Enhanced nonce verification
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!$this->mdlogin_verify_admin_nonce($nonce, 'mdlogin_passkey_admin_nonce')) {
            wp_send_json_error(array(
                'message' => __('Security check failed.', 'multidots-passkey-login'),
            ));
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Insufficient permissions.', 'multidots-passkey-login')));
        }

        // Validate and sanitize user ID
        $user_id = $this->mdlogin_validate_admin_input($_POST['user_id'] ?? 0, 'user_id');
        if (!$user_id) {
            wp_send_json_error(array('message' => __('Invalid user ID.', 'multidots-passkey-login')));
        }

        $user = get_user_by('ID', $user_id);
        if (!$user) {
            wp_send_json_error(array('message' => __('User not found.', 'multidots-passkey-login')));
        }

        $credentials = MDLOGIN_Passkey_Credentials::mdlogin_get_instance();
        $user_credentials = $credentials->mdlogin_get_user_credentials_for_display($user_id);

        wp_send_json_success(array(
            'user' => array(
                'id' => $user->ID,
                'name' => $user->display_name,
                'login' => $user->user_login
            ),
            'credentials' => $user_credentials
        ));
    }

    /**
     * AJAX handler for deleting credential
     */
    public function mdlogin_ajax_delete_credential() {
        // Verify nonce
        if (
            ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ),
                'mdlogin_passkey_admin_nonce'
            )
        ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Security check failed.', 'multidots-passkey-login' ),
                )
            );
        }


        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Insufficient permissions.', 'multidots-passkey-login')));
        }

        $user_id = intval($_POST['user_id'] ?? 0);
        $credential_id = isset( $_POST['credential_id'] )
            ? sanitize_text_field( wp_unslash( $_POST['credential_id'] ) )
            : '';
        
        if (!$user_id || !$credential_id) {
            wp_send_json_error(array('message' => __('Invalid parameters.', 'multidots-passkey-login')));
        }

        $user = get_user_by('ID', $user_id);
        if (!$user) {
            wp_send_json_error(array('message' => __('User not found.', 'multidots-passkey-login')));
        }

        $credentials = MDLOGIN_Passkey_Credentials::mdlogin_get_instance();
        $user_credentials = $credentials->mdlogin_get_user_credentials($user_id);
        
        foreach ($user_credentials as $credential) {
            if ($credential instanceof \Webauthn\PublicKeyCredentialSource) {
                $credential_id_encoded = base64_encode($credential->getPublicKeyCredentialId());
                $credential_id_url = str_replace(array('+', '/'), array('-', '_'), rtrim($credential_id_encoded, '='));
                
                if ($credential_id_url === $credential_id) {
                    $credentials->deleteCredentialSource($credential);
                    wp_send_json_success(array('message' => __('Credential deleted successfully.', 'multidots-passkey-login')));
                }
            }
        }

        wp_send_json_error(array('message' => __('Credential not found.', 'multidots-passkey-login')));
    }

    /**
     * AJAX handler for deleting all credentials for a user
     */
    public function mdlogin_ajax_delete_all_credentials() {
        // Verify nonce
        if (
            ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ),
                'mdlogin_passkey_admin_nonce'
            )
        ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Security check failed.', 'multidots-passkey-login' ),
                )
            );
        }


        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Insufficient permissions.', 'multidots-passkey-login')));
        }

        $user_id = intval($_POST['user_id'] ?? 0);
        
        if (!$user_id) {
            wp_send_json_error(array('message' => __('Invalid user ID.', 'multidots-passkey-login')));
        }

        $user = get_user_by('ID', $user_id);
        if (!$user) {
            wp_send_json_error(array('message' => __('User not found.', 'multidots-passkey-login')));
        }

        $credentials = MDLOGIN_Passkey_Credentials::mdlogin_get_instance();
        $user_credentials = $credentials->mdlogin_get_user_credentials($user_id);
        
        if (empty($user_credentials)) {
            wp_send_json_error(array('message' => __('No credentials found for this user.', 'multidots-passkey-login')));
        }

        // Delete all credentials
        $deleted_count = 0;
        foreach ($user_credentials as $credential) {
            if ($credential instanceof \Webauthn\PublicKeyCredentialSource) {
                $credentials->deleteCredentialSource($credential);
                $deleted_count++;
            }
        }

        if ($deleted_count > 0) {
            wp_send_json_success(array(
                'message' => sprintf(
                    /* translators: %d: Number of credentials deleted */
                    __('%d credentials deleted successfully.', 'multidots-passkey-login'),
                    $deleted_count
                )
            ));
        } else {
            wp_send_json_error(array('message' => __('No credentials were deleted.', 'multidots-passkey-login')));
        }
    }

    // Bulk actions are now handled by WordPress's native list table system

    /**
     * Check WebAuthn support
     *
     * @return bool
     */
    private function mdlogin_check_webauthn_support() {
        // Check if required extensions are available
        $required_extensions = array('openssl', 'json', 'mbstring');
        foreach ($required_extensions as $extension) {
            if (!extension_loaded($extension)) {
                return false;
            }
        }

        // Check if Composer dependencies are available
        if (!class_exists('Webauthn\Server')) {
            return false;
        }

        return true;
    }
} 