<?php
/**
 * WooCommerce Security settings tab.
 *
 * @package Polanger_Dashboard_Tools
 */

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

class PDT_WC_Security_Page {

  /**
   * Save nonce action.
   */
  const NONCE_ACTION = 'pdt_wc_security_save';

  /**
   * Settings service.
   *
   * @var PDT_WC_Security_Settings
   */
  private $settings;

  /**
   * Constructor.
   *
   * @param PDT_WC_Security_Settings $settings Settings service.
   */
  public function __construct( $settings ) {
    $this->settings = $settings;
  }

  /**
   * Register settings tab hooks.
   *
   * @return void
   */
  public function register_hooks() {
    add_filter( 'pdt_settings_tabs', array( $this, 'register_tab' ) );
    add_filter( 'pdt_settings_tab_icons', array( $this, 'register_tab_icon' ) );
    add_action( 'pdt_settings_render_tab_woocommerce', array( $this, 'render_tab' ) );
    add_action( 'admin_init', array( $this, 'maybe_handle_save' ), 25 );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
  }

  /**
   * Register the WooCommerce tab below Comment Guard.
   *
   * @param array $tabs Existing tabs.
   * @return array
   */
  public function register_tab( $tabs ) {
    if ( ! is_array( $tabs ) ) {
      $tabs = array();
    }

    $new = array();

    foreach ( $tabs as $tab_id => $label ) {
      $new[ $tab_id ] = $label;

      if ( 'comments' === $tab_id && ! isset( $new['woocommerce'] ) ) {
        $new['woocommerce'] = __( 'WooCommerce', 'polanger-admin-menu-manager' );
      }
    }

    if ( ! isset( $new['woocommerce'] ) ) {
      $new['woocommerce'] = __( 'WooCommerce', 'polanger-admin-menu-manager' );
    }

    return $new;
  }

  /**
   * Register the WooCommerce tab icon.
   *
   * @param array $icons Existing icon map.
   * @return array
   */
  public function register_tab_icon( $icons ) {
    if ( ! is_array( $icons ) ) {
      $icons = array();
    }

    $icons['woocommerce'] = 'dashicons-cart';

    return $icons;
  }

  /**
   * Save the WooCommerce settings tab.
   *
   * @return void
   */
  public function maybe_handle_save() {
    if ( ! $this->is_woocommerce_settings_tab() ) {
      return;
    }

    if ( empty( $_POST['pdt_wc_security_save'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
      return;
    }

    if ( ! current_user_can( 'manage_options' ) ) {
      return;
    }

    if ( ! isset( $_POST['pdt_wc_security_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['pdt_wc_security_nonce'] ) ), self::NONCE_ACTION ) ) {
      return;
    }

    $raw = isset( $_POST['pdt_wc_security'] ) && is_array( $_POST['pdt_wc_security'] )
      ? wp_unslash( $_POST['pdt_wc_security'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
      : array();

    $this->settings->save_settings( $raw );

    wp_safe_redirect(
      add_query_arg(
        array(
          'page'                  => 'polanger-settings',
          'tab'                   => 'woocommerce',
          'pdt_wc_security_state' => 'saved',
        ),
        admin_url( 'admin.php' )
      )
    );
    exit;
  }

  /**
   * Enqueue styles for the WooCommerce settings tab.
   *
   * @return void
   */
  public function enqueue_assets() {
    if ( ! $this->is_woocommerce_settings_tab() ) {
      return;
    }

    wp_enqueue_style(
      'pdt-wc-security-admin',
      PDT_WC_SECURITY_URL . 'assets/css/woocommerce-security-admin.css',
      array(),
      PDT_WC_SECURITY_VERSION
    );
  }

  /**
   * Render the WooCommerce settings tab.
   *
   * @param bool $is_readonly Whether settings page is read-only.
   * @return void
   */
  public function render_tab( $is_readonly = false ) {
    $settings       = $this->settings->get_settings();
    $modes          = $this->settings->get_modes();
    $active_mode    = $this->settings->get_active_mode_key();
    $recaptcha_url  = admin_url( 'admin.php?page=polanger-settings&tab=recaptcha' );
    $security_url   = admin_url( 'admin.php?page=polanger-settings&tab=security' );
    $current_mode   = isset( $modes[ $active_mode ] ) ? $modes[ $active_mode ] : $modes['balanced'];
    $status_message = ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

    if ( isset( $_GET['pdt_wc_security_state'] ) && 'saved' === sanitize_key( wp_unslash( $_GET['pdt_wc_security_state'] ) ) ) {
      $status_message = __( 'WooCommerce Security settings saved.', 'polanger-admin-menu-manager' );
    }
    ?>
    <div class="pdt-settings-section pdt-wc-security-section">
      <h2><?php esc_html_e( 'WooCommerce Security Layer', 'polanger-admin-menu-manager' ); ?></h2>
      <p class="description">
        <?php esc_html_e( 'Protect WooCommerce customer authentication flows with the existing Polanger reCAPTCHA and 2FA systems, plus a built-in rate limiting layer for login, registration, and password reset abuse.', 'polanger-admin-menu-manager' ); ?>
      </p>

      <?php if ( '' !== $status_message ) : ?>
        <div class="notice notice-success is-dismissible">
          <p><?php echo esc_html( $status_message ); ?></p>
        </div>
      <?php endif; ?>

      <div class="pdt-info-notice pdt-wc-security-intro">
        <span class="dashicons dashicons-shield-alt"></span>
        <div>
          <strong><?php esc_html_e( 'This addon reuses your main security stack', 'polanger-admin-menu-manager' ); ?></strong>
          <p><?php esc_html_e( 'WooCommerce reCAPTCHA locations are managed from the reCAPTCHA tab, and all 2FA challenge timing, retry, and lockout rules continue to come from the 2FA tab.', 'polanger-admin-menu-manager' ); ?></p>
          <div class="pdt-wc-security-links">
            <a class="button button-secondary" href="<?php echo esc_url( $recaptcha_url ); ?>">
              <?php esc_html_e( 'Open reCAPTCHA Settings', 'polanger-admin-menu-manager' ); ?>
            </a>
            <a class="button button-secondary" href="<?php echo esc_url( $security_url ); ?>">
              <?php esc_html_e( 'Open 2FA Settings', 'polanger-admin-menu-manager' ); ?>
            </a>
          </div>
        </div>
      </div>

      <form method="post" class="pdt-settings-form">
        <?php wp_nonce_field( self::NONCE_ACTION, 'pdt_wc_security_nonce' ); ?>
        <input type="hidden" name="pdt_wc_security_save" value="1" />

        <div class="pdt-wc-security-grid">
          <div class="pdt-wc-security-card">
            <h3><?php esc_html_e( 'Rate Limiting', 'polanger-admin-menu-manager' ); ?></h3>
            <p class="description">
              <?php esc_html_e( 'Adds an automatic abuse shield on WooCommerce login failures, account registrations, and lost password requests without adding extra form clutter for customers.', 'polanger-admin-menu-manager' ); ?>
            </p>

            <div class="pdt-form-row">
              <label class="pdt-toggle-switch">
                <input
                  type="checkbox"
                  name="pdt_wc_security[rate_limit_enabled]"
                  value="1"
                  <?php checked( ! empty( $settings['rate_limit_enabled'] ) ); ?>
                  <?php disabled( ! empty( $is_readonly ) ); ?>
                />
                <span class="pdt-toggle-slider"></span>
                <span class="pdt-toggle-label"><?php esc_html_e( 'Enable WooCommerce Rate Limiting', 'polanger-admin-menu-manager' ); ?></span>
              </label>
              <p class="description">
                <?php esc_html_e( 'Recommended to keep enabled. This protection runs automatically across My Account and checkout login prompts.', 'polanger-admin-menu-manager' ); ?>
              </p>
            </div>

            <div class="pdt-form-row">
              <label for="pdt_wc_security_mode"><strong><?php esc_html_e( 'Protection Mode', 'polanger-admin-menu-manager' ); ?></strong></label>
              <select
                id="pdt_wc_security_mode"
                name="pdt_wc_security[protection_mode]"
                class="pdt-wc-security-select"
                <?php disabled( ! empty( $is_readonly ) ); ?>
              >
                <?php foreach ( $modes as $mode_key => $mode ) : ?>
                  <option value="<?php echo esc_attr( $mode_key ); ?>" <?php selected( $active_mode, $mode_key ); ?>>
                    <?php echo esc_html( $mode['label'] ); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <p class="description">
                <?php echo esc_html( $current_mode['description'] ); ?>
              </p>
            </div>
          </div>

          <div class="pdt-wc-security-card">
            <h3><?php esc_html_e( 'What Gets Protected Automatically', 'polanger-admin-menu-manager' ); ?></h3>
            <ul class="pdt-wc-security-list">
              <li><?php esc_html_e( 'Customer login attempts on My Account and WooCommerce login prompts.', 'polanger-admin-menu-manager' ); ?></li>
              <li><?php esc_html_e( 'Customer account registration requests.', 'polanger-admin-menu-manager' ); ?></li>
              <li><?php esc_html_e( 'Lost password and reset-link request abuse.', 'polanger-admin-menu-manager' ); ?></li>
            </ul>

            <div class="pdt-wc-security-mode-summary">
              <div class="pdt-wc-security-mode-summary__item">
                <strong><?php esc_html_e( 'Login failures', 'polanger-admin-menu-manager' ); ?></strong>
                <span><?php echo esc_html( $this->format_limit_summary( $current_mode['limits']['login'] ) ); ?></span>
              </div>
              <div class="pdt-wc-security-mode-summary__item">
                <strong><?php esc_html_e( 'Registration requests', 'polanger-admin-menu-manager' ); ?></strong>
                <span><?php echo esc_html( $this->format_limit_summary( $current_mode['limits']['register'] ) ); ?></span>
              </div>
              <div class="pdt-wc-security-mode-summary__item">
                <strong><?php esc_html_e( 'Password reset requests', 'polanger-admin-menu-manager' ); ?></strong>
                <span><?php echo esc_html( $this->format_limit_summary( $current_mode['limits']['lostpassword'] ) ); ?></span>
              </div>
            </div>
          </div>
        </div>

        <p>
          <button type="submit" class="button button-primary" <?php disabled( ! empty( $is_readonly ) ); ?>>
            <?php esc_html_e( 'Save WooCommerce Settings', 'polanger-admin-menu-manager' ); ?>
          </button>
        </p>
      </form>
    </div>
    <?php
  }

  /**
   * Format a human-readable summary for one limit profile.
   *
   * @param array $profile Limit profile.
   * @return string
   */
  private function format_limit_summary( $profile ) {
    $max_attempts   = isset( $profile['max_attempts'] ) ? absint( $profile['max_attempts'] ) : 0;
    $window_minutes = isset( $profile['window_minutes'] ) ? absint( $profile['window_minutes'] ) : 0;

    return sprintf(
      /* translators: 1: maximum allowed attempts, 2: rolling time window in minutes */
      __( '%1$d requests within %2$d minutes', 'polanger-admin-menu-manager' ),
      $max_attempts,
      $window_minutes
    );
  }

  /**
   * Determine whether the current admin request targets the WooCommerce tab.
   *
   * @return bool
   */
  private function is_woocommerce_settings_tab() {
    if ( ! is_admin() ) {
      return false;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';

    return 'polanger-settings' === $page && 'woocommerce' === $tab;
  }
}
