<?php
/**
 * Authenticator setup tab (provider-only).
 *
 * @package Polanger_Dashboard_Tools
 */

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

class PDT_Authenticator_Page {

  /**
   * TOTP service.
   *
   * @var PDT_Authenticator_TOTP
   */
  private $totp;

  /**
   * Constructor.
   *
   * @param PDT_Authenticator_TOTP $totp TOTP service.
   */
  public function __construct( $totp ) {
    $this->totp = $totp;
  }

  /**
   * Handle setup actions.
   *
   * @return void
   */
  public function maybe_handle_actions() {
    if ( ! current_user_can( 'manage_options' ) ) {
      return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Route check only.
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Route check only.
    $tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';
    if ( 'polanger-settings' !== $page || 'security' !== $tab || ! isset( $_POST['pdt_authenticator_action'] ) ) {
      return;
    }

    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'pdt_authenticator_setup' ) ) {
      return;
    }

    $action = sanitize_key( wp_unslash( $_POST['pdt_authenticator_action'] ) );
    $user_id = get_current_user_id();
    $status = 'noop';

    if ( 'verify_setup' === $action ) {
      $code = isset( $_POST['pdt_authenticator_code'] ) ? sanitize_text_field( wp_unslash( $_POST['pdt_authenticator_code'] ) ) : '';
      if ( $this->totp->verify_code( $user_id, $code ) ) {
        $this->totp->mark_user_enrolled( $user_id );
        
        // Also enable global 2FA settings when authenticator is verified
        $this->enable_2fa_with_authenticator( $user_id );
        
        $status = 'verified';
      } else {
        $status = 'invalid_code';
      }
    } elseif ( 'regenerate_secret' === $action ) {
      // Create pending secret instead of immediate replacement
      $this->totp->create_pending_secret( $user_id );
      
      // Keep 2FA enabled with authenticator method so the form stays visible
      $this->ensure_authenticator_method_active();
      
      $status = 'pending_setup';
    } elseif ( 'verify_pending' === $action ) {
      $code = isset( $_POST['pdt_authenticator_code'] ) ? sanitize_text_field( wp_unslash( $_POST['pdt_authenticator_code'] ) ) : '';
      if ( $this->totp->verify_pending_code( $user_id, $code ) ) {
        // Activate pending secret
        $this->totp->activate_pending_secret( $user_id );
        
        // Generate new recovery keys (security context changed)
        global $pdt_two_factor;
        if ( $pdt_two_factor && method_exists( $pdt_two_factor, 'generate_recovery_keys' ) ) {
          $recovery_keys = $pdt_two_factor->generate_recovery_keys( $user_id );
          set_transient( 'pdt_show_recovery_keys_' . $user_id, $recovery_keys, 60 );
        }
        
        $status = 'pending_verified';
      } else {
        $status = 'invalid_pending_code';
      }
    } elseif ( 'cancel_pending' === $action ) {
      $this->totp->cancel_pending_secret( $user_id );
      $status = 'pending_cancelled';
    } elseif ( 'disable_totp' === $action ) {
      // Also clear any pending secrets
      $this->totp->cancel_pending_secret( $user_id );
      $this->totp->disable_for_user( $user_id );
      
      // Keep 2FA enabled with authenticator method so the form stays visible for re-setup
      $this->ensure_authenticator_method_active();
      
      $status = 'disabled';
    }

    wp_safe_redirect(
      add_query_arg(
        array(
          'page'   => 'polanger-settings',
          'tab'    => 'security',
          'status' => $status,
        ),
        admin_url( 'admin.php' )
      )
    );
    exit;
  }

  /**
   * Enable 2FA with authenticator method when user verifies their setup.
   * Always generates new recovery keys because authenticator verification means
   * a fresh setup (new device, lost phone, app reinstall, etc.)
   *
   * @param int $user_id User ID.
   * @return void
   */
  private function enable_2fa_with_authenticator( $user_id ) {
    global $pdt_settings_page, $pdt_two_factor;
    
    if ( ! $pdt_settings_page || ! method_exists( $pdt_settings_page, 'get_settings' ) ) {
      return;
    }
    
    $settings = $pdt_settings_page->get_settings();
    
    // Enable 2FA and set method to authenticator
    $settings['two_factor_enabled'] = true;
    $settings['two_factor_method'] = 'authenticator';
    
    // Ensure administrator role is in required roles if empty
    if ( empty( $settings['two_factor_roles'] ) ) {
      $settings['two_factor_roles'] = array( 'administrator' );
    }
    
    $pdt_settings_page->update_settings( $settings );
    
    // Always generate new recovery keys when authenticator is verified
    // Because verification means a fresh authenticator setup:
    // - User changed phone
    // - User lost access to authenticator app
    // - User reinstalled the app
    // - User generated new secret
    // In all these cases, user should get fresh recovery keys
    if ( $pdt_two_factor && method_exists( $pdt_two_factor, 'generate_recovery_keys' ) ) {
      $recovery_keys = $pdt_two_factor->generate_recovery_keys( $user_id );
      
      // Store recovery keys in transient to show modal after redirect
      set_transient( 'pdt_show_recovery_keys_' . $user_id, $recovery_keys, 60 );
    }
  }

  /**
   * Ensure 2FA is enabled with authenticator method.
   * Used to keep the authenticator form visible after regenerate/disable actions.
   * Does not generate recovery keys.
   *
   * @return void
   */
  private function ensure_authenticator_method_active() {
    global $pdt_settings_page;
    
    if ( ! $pdt_settings_page || ! method_exists( $pdt_settings_page, 'get_settings' ) ) {
      return;
    }
    
    $settings = $pdt_settings_page->get_settings();
    
    // Enable 2FA and set method to authenticator
    $settings['two_factor_enabled'] = true;
    $settings['two_factor_method'] = 'authenticator';
    
    // Ensure administrator role is in required roles if empty
    if ( empty( $settings['two_factor_roles'] ) ) {
      $settings['two_factor_roles'] = array( 'administrator' );
    }
    
    $pdt_settings_page->update_settings( $settings );
  }

  /**
   * Enqueue assets for security tab.
   *
   * @param string $hook Admin page hook.
   * @return void
   */
  public function enqueue_assets( $hook ) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Route check only.
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Route check only.
    $tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';

    // Check if we're on the settings page with security tab
    if ( 'polanger-settings' !== $page || 'security' !== $tab ) {
      return;
    }

    // Build correct URL using main plugin file as reference
    $addon_url = plugins_url( 'addons/polanger-authenticator/', PDT_PLUGIN_FILE );

    wp_enqueue_style(
      'pdt-authenticator-settings',
      $addon_url . 'assets/css/authenticator.css',
      array(),
      PDT_VERSION
    );

    wp_enqueue_script(
      'pdt-authenticator-settings',
      $addon_url . 'assets/js/authenticator.js',
      array(),
      PDT_VERSION,
      true
    );

    wp_localize_script(
      'pdt-authenticator-settings',
      'pdtAuthenticatorI18n',
      array(
        'copySuccess' => __( 'Copied!', 'polanger-admin-menu-manager' ),
      )
    );
  }

  /**
   * Render authenticator setup section inside 2FA method selector.
   *
   * @param int  $user_id     Current user ID.
   * @param bool $is_readonly Whether read-only mode is active.
   * @return void
   */
  public function render_tab( $user_id = 0, $is_readonly = false ) {
    if ( ! $user_id ) {
      $user_id = get_current_user_id();
    }
    $secret = $this->totp->get_or_create_secret( $user_id );
    $provisioning_uri = $this->totp->get_provisioning_uri( $user_id );
    $is_enrolled = $this->totp->is_user_enrolled( $user_id );
    $has_pending = $this->totp->has_pending_secret( $user_id );
    $pending_secret = $has_pending ? $this->totp->get_pending_secret( $user_id ) : '';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Status after redirect.
    $status = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
    ?>
    
    <div class="pdt-authenticator-setup">
      
      <!-- Status Messages -->
      <?php if ( 'verified' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-success">
          <span class="dashicons dashicons-yes-alt"></span>
          <div>
            <strong><?php esc_html_e( 'Setup Complete!', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'Your authenticator app is now linked to your account. You will use it to verify your identity when logging in.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php elseif ( 'invalid_code' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-error">
          <span class="dashicons dashicons-warning"></span>
          <div>
            <strong><?php esc_html_e( 'Verification Failed', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'The code you entered is incorrect. Make sure you\'re using the correct secret key and your device time is synchronized.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php elseif ( 'pending_setup' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-info">
          <span class="dashicons dashicons-update"></span>
          <div>
            <strong><?php esc_html_e( 'New Secret Generated', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'Your new secret is ready. Add it to your authenticator app and verify it below. Your old authenticator will continue working until you verify the new one.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php elseif ( 'pending_verified' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-success">
          <span class="dashicons dashicons-yes-alt"></span>
          <div>
            <strong><?php esc_html_e( 'New Secret Activated!', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'Your authenticator has been updated successfully. New recovery keys have been generated.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php elseif ( 'pending_cancelled' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-info">
          <span class="dashicons dashicons-undo"></span>
          <div>
            <strong><?php esc_html_e( 'Rotation Cancelled', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'Secret rotation cancelled. Your existing authenticator remains active.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php elseif ( 'invalid_pending_code' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-error">
          <span class="dashicons dashicons-warning"></span>
          <div>
            <strong><?php esc_html_e( 'Verification Failed', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'The code for the new secret is incorrect. Make sure you added the NEW secret to your authenticator app.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php elseif ( 'disabled' === $status ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-warning">
          <span class="dashicons dashicons-dismiss"></span>
          <div>
            <strong><?php esc_html_e( 'Authenticator Disabled', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'Authenticator has been removed from your account. You can set it up again anytime.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php endif; ?>

      <!-- Current Status Banner -->
      <div class="pdt-auth-status-banner <?php echo $is_enrolled ? 'is-active' : 'is-pending'; ?>">
        <div class="pdt-auth-status-icon">
          <span class="dashicons <?php echo $is_enrolled ? 'dashicons-shield' : 'dashicons-clock'; ?>"></span>
        </div>
        <div class="pdt-auth-status-content">
          <strong>
            <?php echo $is_enrolled ? esc_html__( 'Authenticator Active', 'polanger-admin-menu-manager' ) : esc_html__( 'Setup Required', 'polanger-admin-menu-manager' ); ?>
          </strong>
          <p>
            <?php echo $is_enrolled 
              ? esc_html__( 'Your authenticator app is configured and ready. You\'ll be asked for a code when logging in.', 'polanger-admin-menu-manager' ) 
              : esc_html__( 'Complete the setup below to enable authenticator-based verification for your account.', 'polanger-admin-menu-manager' ); 
            ?>
          </p>
        </div>
      </div>

      <?php if ( $is_readonly ) : ?>
        <div class="pdt-auth-notice pdt-auth-notice-warning">
          <span class="dashicons dashicons-lock"></span>
          <div>
            <strong><?php esc_html_e( 'Read-Only Mode', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'You have read-only access. Contact your administrator to modify authenticator settings.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      <?php endif; ?>

      <?php if ( $has_pending ) : ?>
      <!-- Pending Secret Rotation -->
      <div class="pdt-auth-pending-section" style="background: #fffbeb; border: 1px solid #fcd34d; border-radius: 8px; padding: 20px; margin-bottom: 24px;">
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 16px;">
          <span class="dashicons dashicons-warning" style="color: #d97706; font-size: 24px; width: 24px; height: 24px;"></span>
          <h3 style="margin: 0; color: #92400e;"><?php esc_html_e( 'Pending Secret Rotation', 'polanger-admin-menu-manager' ); ?></h3>
        </div>
        <p style="color: #78350f; margin: 0 0 16px;">
          <?php esc_html_e( 'A new secret is waiting to be verified. Your old authenticator will continue working until you verify the new one.', 'polanger-admin-menu-manager' ); ?>
        </p>
        
        <div class="pdt-auth-secret-box" style="background: #fff; border-color: #fcd34d;">
          <div class="pdt-auth-secret-label">
            <span class="dashicons dashicons-admin-network"></span>
            <span><?php esc_html_e( 'New Secret Key', 'polanger-admin-menu-manager' ); ?></span>
          </div>
          <div class="pdt-auth-secret-value">
            <code id="pdt-pending-secret"><?php echo esc_html( $pending_secret ); ?></code>
            <button type="button" class="pdt-auth-copy-btn" data-pdt-copy-secret="<?php echo esc_attr( $pending_secret ); ?>" title="<?php esc_attr_e( 'Copy to clipboard', 'polanger-admin-menu-manager' ); ?>">
              <span class="dashicons dashicons-clipboard"></span>
              <span class="pdt-copy-text"><?php esc_html_e( 'Copy', 'polanger-admin-menu-manager' ); ?></span>
            </button>
          </div>
        </div>
        
        <form method="post" class="pdt-auth-verify-form" style="margin-top: 16px;">
          <?php wp_nonce_field( 'pdt_authenticator_setup' ); ?>
          <input type="hidden" name="pdt_authenticator_action" value="verify_pending" />
          
          <p style="color: #64748b; font-size: 13px; margin: 0 0 8px;">
            <?php esc_html_e( 'Add the NEW secret to your authenticator app, then enter the code:', 'polanger-admin-menu-manager' ); ?>
          </p>
          
          <div class="pdt-auth-code-input-wrapper">
            <input 
              type="text" 
              name="pdt_authenticator_code" 
              class="pdt-auth-code-input" 
              placeholder="000000"
              maxlength="6" 
              pattern="[0-9]{6}" 
              inputmode="numeric"
              autocomplete="one-time-code"
              required 
              <?php echo $is_readonly ? 'disabled' : ''; ?> 
            />
            <button type="submit" class="button button-primary pdt-auth-verify-btn" <?php echo $is_readonly ? 'disabled' : ''; ?>>
              <span class="dashicons dashicons-yes"></span>
              <?php esc_html_e( 'Verify & Activate', 'polanger-admin-menu-manager' ); ?>
            </button>
          </div>
        </form>
        
        <form method="post" style="margin-top: 12px;">
          <?php wp_nonce_field( 'pdt_authenticator_setup' ); ?>
          <input type="hidden" name="pdt_authenticator_action" value="cancel_pending" />
          <button type="submit" class="button" <?php echo $is_readonly ? 'disabled' : ''; ?>>
            <span class="dashicons dashicons-undo"></span>
            <?php esc_html_e( 'Cancel Rotation', 'polanger-admin-menu-manager' ); ?>
          </button>
          <span style="color: #64748b; font-size: 13px; margin-left: 8px;">
            <?php esc_html_e( 'Keep using your existing authenticator', 'polanger-admin-menu-manager' ); ?>
          </span>
        </form>
      </div>
      <?php endif; ?>

      <!-- Setup Steps -->
      <div class="pdt-auth-steps">
        
        <!-- Step 1: Add to App -->
        <div class="pdt-auth-step">
          <div class="pdt-auth-step-header">
            <div class="pdt-auth-step-number">1</div>
            <div class="pdt-auth-step-title">
              <h3><?php esc_html_e( 'Add Account to Your Authenticator App', 'polanger-admin-menu-manager' ); ?></h3>
              <p><?php esc_html_e( 'Open Google Authenticator or Microsoft Authenticator on your phone and add a new account.', 'polanger-admin-menu-manager' ); ?></p>
            </div>
          </div>
          
          <div class="pdt-auth-step-content">
            <!-- Secret Key Section -->
            <div class="pdt-auth-secret-box">
              <div class="pdt-auth-secret-label">
                <span class="dashicons dashicons-admin-network"></span>
                <span><?php esc_html_e( 'Your Secret Key', 'polanger-admin-menu-manager' ); ?></span>
              </div>
              <div class="pdt-auth-secret-value">
                <code id="pdt-authenticator-secret"><?php echo esc_html( $secret ); ?></code>
                <button type="button" class="pdt-auth-copy-btn" data-pdt-copy-secret="<?php echo esc_attr( $secret ); ?>" title="<?php esc_attr_e( 'Copy to clipboard', 'polanger-admin-menu-manager' ); ?>">
                  <span class="dashicons dashicons-clipboard"></span>
                  <span class="pdt-copy-text"><?php esc_html_e( 'Copy', 'polanger-admin-menu-manager' ); ?></span>
                </button>
              </div>
              <p class="pdt-auth-secret-help"><?php esc_html_e( 'Enter this key manually in your authenticator app when adding a new account.', 'polanger-admin-menu-manager' ); ?></p>
            </div>

            <!-- Provisioning URI Section -->
            <details class="pdt-auth-advanced">
              <summary>
                <span class="dashicons dashicons-admin-tools"></span>
                <?php esc_html_e( 'Advanced: Provisioning URI for QR Code Tools', 'polanger-admin-menu-manager' ); ?>
              </summary>
              <div class="pdt-auth-advanced-content">
                <p class="description"><?php esc_html_e( 'Use this URI with a QR code generator if you prefer scanning. Most users can simply enter the secret key manually.', 'polanger-admin-menu-manager' ); ?></p>
                <textarea id="pdt-authenticator-uri" class="pdt-auth-uri-textarea" rows="2" readonly onclick="this.select()"><?php echo esc_textarea( $provisioning_uri ); ?></textarea>
              </div>
            </details>
          </div>
        </div>

        <!-- Step 2: Verify -->
        <div class="pdt-auth-step">
          <div class="pdt-auth-step-header">
            <div class="pdt-auth-step-number">2</div>
            <div class="pdt-auth-step-title">
              <h3><?php esc_html_e( 'Verify Your Setup', 'polanger-admin-menu-manager' ); ?></h3>
              <p><?php esc_html_e( 'Enter the 6-digit code shown in your authenticator app to confirm the connection.', 'polanger-admin-menu-manager' ); ?></p>
            </div>
          </div>
          
          <div class="pdt-auth-step-content">
            <form method="post" class="pdt-auth-verify-form">
              <?php wp_nonce_field( 'pdt_authenticator_setup' ); ?>
              <input type="hidden" name="pdt_authenticator_action" value="verify_setup" />
              
              <div class="pdt-auth-code-input-wrapper">
                <label for="pdt_authenticator_code" class="screen-reader-text"><?php esc_html_e( 'Verification Code', 'polanger-admin-menu-manager' ); ?></label>
                <input 
                  type="text" 
                  id="pdt_authenticator_code" 
                  name="pdt_authenticator_code" 
                  class="pdt-auth-code-input" 
                  placeholder="000000"
                  maxlength="6" 
                  pattern="[0-9]{6}" 
                  inputmode="numeric"
                  autocomplete="one-time-code"
                  required 
                  <?php echo $is_readonly ? 'disabled' : ''; ?> 
                />
                <button type="submit" class="button button-primary pdt-auth-verify-btn" <?php echo $is_readonly ? 'disabled' : ''; ?>>
                  <span class="dashicons dashicons-yes"></span>
                  <?php esc_html_e( 'Verify & Activate', 'polanger-admin-menu-manager' ); ?>
                </button>
              </div>
              
              <p class="pdt-auth-code-help">
                <span class="dashicons dashicons-info-outline"></span>
                <?php esc_html_e( 'The code refreshes every 30 seconds. Make sure to enter the current code.', 'polanger-admin-menu-manager' ); ?>
              </p>
            </form>
          </div>
        </div>

      </div>

      <!-- Management Actions -->
      <div class="pdt-auth-management">
        <h4><?php esc_html_e( 'Manage Authenticator', 'polanger-admin-menu-manager' ); ?></h4>
        <p class="description"><?php esc_html_e( 'These actions help you troubleshoot or reset your authenticator setup if needed.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-auth-actions">
          <form method="post" class="pdt-auth-action-form">
            <?php wp_nonce_field( 'pdt_authenticator_setup' ); ?>
            <input type="hidden" name="pdt_authenticator_action" value="regenerate_secret" />
            <button type="submit" class="button button-secondary" <?php echo $is_readonly ? 'disabled' : ''; ?>>
              <span class="dashicons dashicons-update"></span>
              <?php esc_html_e( 'Generate New Secret', 'polanger-admin-menu-manager' ); ?>
            </button>
            <span class="pdt-auth-action-desc"><?php esc_html_e( 'Creates a new secret key. Use if you lost access to your app.', 'polanger-admin-menu-manager' ); ?></span>
          </form>

          <form method="post" class="pdt-auth-action-form">
            <?php wp_nonce_field( 'pdt_authenticator_setup' ); ?>
            <input type="hidden" name="pdt_authenticator_action" value="disable_totp" />
            <button type="submit" class="button pdt-auth-disable-btn" <?php echo $is_readonly ? 'disabled' : ''; ?>>
              <span class="dashicons dashicons-dismiss"></span>
              <?php esc_html_e( 'Disable Authenticator', 'polanger-admin-menu-manager' ); ?>
            </button>
            <span class="pdt-auth-action-desc"><?php esc_html_e( 'Removes authenticator from your account completely.', 'polanger-admin-menu-manager' ); ?></span>
          </form>
        </div>
      </div>

    </div>
    <?php
  }
}
