<?php
/**
 * reCAPTCHA Addon - Admin Settings Page
 *
 * Registers a "reCAPTCHA" tab on the Polanger Settings screen and renders
 * the configuration UI including key inputs, version toggle, location
 * checkboxes, and a migration status notice.
 *
 * @package Polanger_Dashboard_Tools
 */

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

/**
 * reCAPTCHA Admin Page.
 */
class PDT_Recaptcha_Page {

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

  /**
   * Service.
   *
   * @var PDT_Recaptcha_Service
   */
  private $service;

  /**
   * Nonce action used for settings save.
   *
   * @var string
   */
  const NONCE_ACTION = 'pdt_recaptcha_save';

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

  // -------------------------------------------------------------------------
  // Tab registration
  // -------------------------------------------------------------------------

  /**
   * Register the "reCAPTCHA" tab.
   *
   * @param array $tabs Existing tabs.
   * @return array
   */
  public function register_tab( $tabs ) {
    $tabs['recaptcha'] = __( 'reCAPTCHA', 'polanger-admin-menu-manager' );
    return $tabs;
  }

  /**
   * Register the tab icon.
   *
   * @param array $icons Existing icons.
   * @return array
   */
  public function register_tab_icon( $icons ) {
    $icons['recaptcha'] = 'dashicons-shield-alt';
    return $icons;
  }

  // -------------------------------------------------------------------------
  // Settings save
  // -------------------------------------------------------------------------

  /**
   * Handle settings form submission.
   *
   * @return void
   */
  public function maybe_handle_save() {
    // phpcs:disable WordPress.Security.NonceVerification.Missing
    if ( empty( $_POST['pdt_recaptcha_save'] ) ) {
      return;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Missing

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

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

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

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

    add_action(
      'pdt_recaptcha_after_save',
      function () {
        echo '<div class="notice notice-success is-dismissible pdt-recaptcha-notice"><p>'
          . esc_html__( 'reCAPTCHA settings saved.', 'polanger-admin-menu-manager' )
          . '</p></div>';
      }
    );
  }

  // -------------------------------------------------------------------------
  // Assets
  // -------------------------------------------------------------------------

  /**
   * Enqueue assets when on the Settings page.
   *
   * @param string $hook_suffix Current admin page hook.
   * @return void
   */
  public function enqueue_assets( $hook_suffix ) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( ! isset( $_GET['page'] ) || 'polanger-settings' !== sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
      return;
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( ! isset( $_GET['tab'] ) || 'recaptcha' !== sanitize_text_field( wp_unslash( $_GET['tab'] ) ) ) {
      return;
    }

    wp_enqueue_style(
      'pdt-recaptcha-admin',
      plugins_url( 'addons/recaptcha/assets/css/recaptcha-admin.css', PDT_PLUGIN_FILE ),
      array(),
      PDT_VERSION
    );
  }

  // -------------------------------------------------------------------------
  // Tab rendering
  // -------------------------------------------------------------------------

  /**
   * Render the reCAPTCHA settings tab.
   *
   * @return void
   */
  public function render_tab() {
    do_action( 'pdt_recaptcha_after_save' );

    $s                 = $this->settings->get_settings();
    $migrated          = get_option( PDT_Recaptcha_Settings::MIGRATION_FLAG );
    $location_settings = $this->settings->get_location_definitions();
    ?>
    <form method="post" action="">
      <?php wp_nonce_field( self::NONCE_ACTION, 'pdt_recaptcha_nonce' ); ?>
      <input type="hidden" name="pdt_recaptcha_save" value="1" />

      <?php if ( $migrated && ! empty( $s['site_key'] ) ) : ?>
        <div class="pdt-rc-notice">
          <span class="dashicons dashicons-migrate"></span>
          <div>
            <strong><?php esc_html_e( 'Keys migrated', 'polanger-admin-menu-manager' ); ?></strong><br>
            <?php esc_html_e( 'Your reCAPTCHA keys were automatically imported from the Login Page settings. The Login Page module now reads keys from here.', 'polanger-admin-menu-manager' ); ?>
          </div>
        </div>
      <?php endif; ?>

      <?php if ( ! $this->service->is_configured() ) : ?>
        <div class="pdt-rc-notice pdt-rc-notice-warn">
          <span class="dashicons dashicons-warning"></span>
          <div>
            <?php
            printf(
              /* translators: %s: link to Google reCAPTCHA Admin console */
              wp_kses_post( __( 'Enter your Site Key and Secret Key to enable reCAPTCHA. Get free keys from %s.', 'polanger-admin-menu-manager' ) ),
              '<a href="https://www.google.com/recaptcha/admin" target="_blank" rel="noopener">'
                . esc_html__( 'Google reCAPTCHA Admin', 'polanger-admin-menu-manager' )
                . '</a>'
            );
            ?>
          </div>
        </div>
      <?php endif; ?>

      <div class="pdt-rc-section">
        <h3 class="pdt-rc-section-title">
          <span class="dashicons dashicons-admin-network"></span>
          <?php esc_html_e( 'API Keys', 'polanger-admin-menu-manager' ); ?>
        </h3>
        <div class="pdt-rc-card">
          <p class="pdt-rc-card-desc">
            <?php
            printf(
              /* translators: %s: link to Google reCAPTCHA Admin console */
              wp_kses_post( __( 'Keys are shared across all integrations (login, comments, etc.). Get yours at %s.', 'polanger-admin-menu-manager' ) ),
              '<a href="https://www.google.com/recaptcha/admin" target="_blank" rel="noopener">'
                . esc_html__( 'Google reCAPTCHA Admin', 'polanger-admin-menu-manager' )
                . '</a>'
            );
            ?>
          </p>

          <div class="pdt-rc-option">
            <div class="pdt-rc-option-content">
              <span class="pdt-rc-option-label"><?php esc_html_e( 'Site Key', 'polanger-admin-menu-manager' ); ?></span>
              <input
                type="text"
                name="pdt_recaptcha[site_key]"
                value="<?php echo esc_attr( $s['site_key'] ); ?>"
                placeholder="6Lc..."
                class="pdt-rc-input"
                autocomplete="off"
              />
            </div>
          </div>

          <div class="pdt-rc-option">
            <div class="pdt-rc-option-content">
              <span class="pdt-rc-option-label"><?php esc_html_e( 'Secret Key', 'polanger-admin-menu-manager' ); ?></span>
              <input
                type="password"
                name="pdt_recaptcha[secret_key]"
                value="<?php echo esc_attr( $s['secret_key'] ); ?>"
                placeholder="6Lc..."
                class="pdt-rc-input"
                autocomplete="new-password"
              />
            </div>
          </div>
        </div>
      </div>

      <div class="pdt-rc-section">
        <h3 class="pdt-rc-section-title">
          <span class="dashicons dashicons-tag"></span>
          <?php esc_html_e( 'Version', 'polanger-admin-menu-manager' ); ?>
        </h3>
        <div class="pdt-rc-card">
          <p class="pdt-rc-card-desc">
            <?php esc_html_e( 'v2 shows a checkbox widget. v3 is invisible and assigns a risk score - use a separate key pair for each version.', 'polanger-admin-menu-manager' ); ?>
          </p>

          <div class="pdt-rc-option">
            <div class="pdt-rc-option-content">
              <span class="pdt-rc-option-label"><?php esc_html_e( 'reCAPTCHA Version', 'polanger-admin-menu-manager' ); ?></span>
              <div class="pdt-rc-radio-group">
                <label class="pdt-rc-radio">
                  <input type="radio" name="pdt_recaptcha[version]" value="v2" <?php checked( $s['version'], 'v2' ); ?> />
                  <span><?php esc_html_e( 'v2 - Checkbox', 'polanger-admin-menu-manager' ); ?></span>
                </label>
                <label class="pdt-rc-radio">
                  <input type="radio" name="pdt_recaptcha[version]" value="v3" <?php checked( $s['version'], 'v3' ); ?> />
                  <span><?php esc_html_e( 'v3 - Invisible', 'polanger-admin-menu-manager' ); ?></span>
                </label>
              </div>
            </div>
          </div>

          <div class="pdt-rc-option">
            <div class="pdt-rc-option-content">
              <span class="pdt-rc-option-label"><?php esc_html_e( 'v3 Score Threshold', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-rc-option-desc">
                <?php esc_html_e( 'Only used when v3 is selected. Requests scoring below this value are rejected. Google recommends 0.5.', 'polanger-admin-menu-manager' ); ?>
              </span>
              <input
                type="number"
                name="pdt_recaptcha[v3_threshold]"
                value="<?php echo esc_attr( number_format( (float) $s['v3_threshold'], 1 ) ); ?>"
                min="0"
                max="1"
                step="0.1"
                class="pdt-rc-input pdt-rc-number"
              />
            </div>
          </div>
        </div>
      </div>

      <div class="pdt-rc-section">
        <h3 class="pdt-rc-section-title">
          <span class="dashicons dashicons-location"></span>
          <?php esc_html_e( 'Where to Enable', 'polanger-admin-menu-manager' ); ?>
        </h3>
        <div class="pdt-rc-card">
          <p class="pdt-rc-card-desc">
            <?php esc_html_e( 'Select which forms should be protected. WordPress login-area forms require the Login Page module. WooCommerce options appear automatically when the WooCommerce Security addon is active.', 'polanger-admin-menu-manager' ); ?>
          </p>

          <?php foreach ( $location_settings as $location_key => $location ) : ?>
            <div class="pdt-rc-option">
              <label class="pdt-rc-toggle">
                <input type="checkbox" name="pdt_recaptcha[<?php echo esc_attr( $location_key ); ?>]" value="1" <?php checked( ! empty( $s[ $location_key ] ) ); ?> />
                <span class="pdt-rc-toggle-slider"></span>
              </label>
              <div class="pdt-rc-option-content">
                <span class="pdt-rc-option-label"><?php echo esc_html( $location['label'] ); ?></span>
                <?php if ( ! empty( $location['description'] ) ) : ?>
                  <span class="pdt-rc-option-desc"><?php echo esc_html( $location['description'] ); ?></span>
                <?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="pdt-rc-section">
        <div class="pdt-rc-notice">
          <span class="dashicons dashicons-info"></span>
          <div>
            <strong><?php esc_html_e( 'Centralized Management', 'polanger-admin-menu-manager' ); ?></strong><br>
            <?php esc_html_e( 'All reCAPTCHA settings are managed from this single location. The addon automatically integrates with the Login Page module and Comment forms. Enable the locations above to activate protection on the corresponding forms.', 'polanger-admin-menu-manager' ); ?>
          </div>
        </div>
      </div>

      <div class="pdt-rc-submit">
        <?php submit_button( __( 'Save Settings', 'polanger-admin-menu-manager' ), 'primary', 'submit', false ); ?>
      </div>
    </form>
    <?php
  }
}
