<?php
/**
 * 2FA admin tab — settings + per-user status with admin-rescue actions.
 *
 * @package Brainwerk Security Suite
 */

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

if ( ! empty( $_POST['shieldforge_2fa_admin_action'] ) && check_admin_referer( 'shieldforge_2fa_admin' ) && current_user_can( Shieldforge_Admin::CAP ) ) {
    $a = sanitize_key( wp_unslash( $_POST['shieldforge_2fa_admin_action'] ) );
    if ( 'rescue_disable' === $a ) {
        $target = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
        if ( $target && current_user_can( 'edit_user', $target ) ) {
            Shieldforge_TwoFactor::disable_for_user( $target, 'admin_rescue' );
            add_settings_error( 'brainwerk-security-suite', 'sf_2fa_rescue', sprintf(
                /* translators: %s: username */
                esc_html__( '2FA disabled (rescue) for user: %s', 'brainwerk-security-suite' ),
                '<strong>' . esc_html( get_userdata( $target )->user_login ) . '</strong>'
            ), 'updated' );
        }
    }
}

$enabled       = (bool) Shieldforge_Settings::get( 'twofactor_enabled', true );
$force_roles   = (array) Shieldforge_Settings::get( 'twofactor_force_roles', array() );
$wp_roles      = wp_roles()->roles; // [slug => ['name' => ..., ...]]

// Pull users that have 2FA-related meta (enabled OR pending). Not paginated
// because realistically the count of *2FA-active* users on a small/medium
// site is tiny; we cap at 100 so a giant network doesn't OOM the page.
global $wpdb;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aggregated multi-meta-key read with no WP_User_Query equivalent; capability-gated admin view; not cacheable across usermeta writes.
$user_rows = $wpdb->get_results( $wpdb->prepare(
    "SELECT u.ID, u.user_login, u.user_email,
            MAX(CASE WHEN um.meta_key = 'shieldforge_2fa_enabled'   THEN um.meta_value END) AS enabled_flag,
            MAX(CASE WHEN um.meta_key = 'shieldforge_2fa_recovery'  THEN um.meta_value END) AS recovery_blob,
            MAX(CASE WHEN um.meta_key = 'shieldforge_2fa_last_used' THEN um.meta_value END) AS last_used
     FROM {$wpdb->users} u
     INNER JOIN {$wpdb->usermeta} um ON um.user_id = u.ID
     WHERE um.meta_key IN ('shieldforge_2fa_enabled','shieldforge_2fa_pending_secret','shieldforge_2fa_recovery','shieldforge_2fa_last_used')
     GROUP BY u.ID
     ORDER BY u.user_login ASC
     LIMIT %d", 100
) );
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

// Total user count so we can show coverage ("X of Y admins have 2FA").
$admin_count = count_users();
?>

<?php
$current_uid = get_current_user_id();
$me_enrolled = $current_uid ? Shieldforge_TwoFactor::is_enabled_for_user( $current_uid ) : false;
?>
<?php if ( $current_uid && ! $me_enrolled ) : ?>
<div class="notice notice-warning inline" style="margin:0 0 16px; padding:14px 18px;">
    <p style="margin:0; font-size:14px;">
        <strong><?php esc_html_e( 'Your account does not have 2FA enabled yet.', 'brainwerk-security-suite' ); ?></strong>
        <?php esc_html_e( 'This tab is the admin overview — the actual setup form is on your user profile.', 'brainwerk-security-suite' ); ?>
        <br>
        <a href="<?php echo esc_url( admin_url( 'profile.php' ) . '#shieldforge-2fa' ); ?>" class="button button-primary" style="margin-top:8px;">
            <?php esc_html_e( 'Set up 2FA on my profile →', 'brainwerk-security-suite' ); ?>
        </a>
    </p>
</div>
<?php endif; ?>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Two-factor authentication', 'brainwerk-security-suite' ); ?></h2>
    <p class="muted">
        <?php esc_html_e( 'Standard TOTP (RFC 6238): works with Google Authenticator, Authy, Microsoft Authenticator, 2FAS, FreeOTP, Aegis. Each user enrolls themselves on their own profile page.', 'brainwerk-security-suite' ); ?>
        <strong><?php esc_html_e( 'No external services involved — secrets and recovery codes never leave your database.', 'brainwerk-security-suite' ); ?></strong>
    </p>

    <form method="post" action="">
        <?php wp_nonce_field( Shieldforge_Admin::NONCE ); ?>
        <input type="hidden" name="shieldforge_action" value="save_settings">
        <input type="hidden" name="shieldforge_tab_keys[]" value="twofactor_enabled">

        <table class="form-table" role="presentation">
            <tr>
                <th scope="row"><?php esc_html_e( 'Enable 2FA module', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[twofactor_enabled]" value="1" <?php checked( $enabled ); ?>>
                        <?php esc_html_e( 'Allow users to enable two-factor authentication on their profile.', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Force 2FA for these roles', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <?php foreach ( $wp_roles as $slug => $role ) : ?>
                        <label style="display:inline-block; margin:0 16px 6px 0">
                            <input type="checkbox"
                                   name="shieldforge[twofactor_force_roles][]"
                                   value="<?php echo esc_attr( $slug ); ?>"
                                   <?php checked( in_array( $slug, $force_roles, true ) ); ?>>
                            <?php echo esc_html( $role['name'] ); ?>
                        </label>
                    <?php endforeach; ?>
                    <p class="description">
                        <?php esc_html_e( 'Users in these roles see a warning on their profile until they complete setup. Setup is still self-service — admins cannot enroll on someone\'s behalf.', 'brainwerk-security-suite' ); ?>
                    </p>
                </td>
            </tr>
        </table>

        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Users with 2FA configured', 'brainwerk-security-suite' ); ?></h2>
    <?php if ( empty( $user_rows ) ) : ?>
        <p class="muted"><?php esc_html_e( 'No users have set up 2FA yet. Each user enables it from their own profile page (Users → Profile → Two-factor authentication).', 'brainwerk-security-suite' ); ?></p>
    <?php else : ?>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'User', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Status', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Recovery codes', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Last used', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Rescue action', 'brainwerk-security-suite' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $user_rows as $r ) :
                    $is_on    = (int) $r->enabled_flag === 1;
                    $rec_left = 0;
                    if ( $r->recovery_blob ) {
                        $arr = maybe_unserialize( $r->recovery_blob );
                        $rec_left = is_array( $arr ) ? count( $arr ) : 0;
                    }
                    $last = $r->last_used ? human_time_diff( (int) $r->last_used, time() ) . ' ' . __( 'ago', 'brainwerk-security-suite' ) : __( 'never', 'brainwerk-security-suite' );
                ?>
                    <tr>
                        <td>
                            <a href="<?php echo esc_url( admin_url( 'user-edit.php?user_id=' . (int) $r->ID ) ); ?>#shieldforge-2fa">
                                <strong><?php echo esc_html( $r->user_login ); ?></strong>
                            </a>
                            <br><span class="muted" style="font-size:11px"><?php echo esc_html( $r->user_email ); ?></span>
                        </td>
                        <td>
                            <?php if ( $is_on ) : ?>
                                <span style="color:#2d6a2d; font-weight:600">&#x25CF; <?php esc_html_e( 'active', 'brainwerk-security-suite' ); ?></span>
                            <?php else : ?>
                                <span class="muted">&#x25CB; <?php esc_html_e( 'pending setup', 'brainwerk-security-suite' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo (int) $rec_left; ?></td>
                        <td><?php echo esc_html( $last ); ?></td>
                        <td>
                            <?php if ( $is_on ) : ?>
                                <form method="post" action="" style="display:inline">
                                    <?php wp_nonce_field( 'shieldforge_2fa_admin' ); ?>
                                    <input type="hidden" name="shieldforge_2fa_admin_action" value="rescue_disable">
                                    <input type="hidden" name="user_id" value="<?php echo (int) $r->ID; ?>">
                                    <button type="submit" class="button-link" onclick="return confirm('<?php echo esc_js( sprintf( __( 'Disable 2FA for %s? Use only when the user lost both their authenticator and recovery codes.', 'brainwerk-security-suite' ), $r->user_login ) ); ?>');"><?php esc_html_e( 'Rescue: disable', 'brainwerk-security-suite' ); ?></button>
                                </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <p class="description" style="margin-top:8px"><?php esc_html_e( 'Capped at 100 rows. Use the user-edit screen for individual user management.', 'brainwerk-security-suite' ); ?></p>
    <?php endif; ?>
</div>
