<?php

namespace ModernFields\WordPress\Security;

defined('ABSPATH') || exit;

/**
 * Utilities for nonce validation, role checking, and admin page detection.
 *
 * @since 1.0.0
 */
abstract class SecurityHelper
{
  /**
   * Check the validity of a nonce from the $_POST data.
   *
   * @since 1.0.0
   * @param string $nonce  The key name of the nonce field in $_POST.
   * @param string $action The action name for which the nonce was generated.
   */
  public static function checkNonce(string $nonce, string $action): bool
  {
    if (!isset($_POST[$nonce])) {
      return false;
    }

    $nonce = sanitize_text_field(wp_unslash($_POST[$nonce]));

    return (bool) wp_verify_nonce($nonce, $action);
  }

  /**
   * Check if the current user has at least one of the required roles.
   *
   * @since 1.0.0
   * @param array $roles The roles to check.
   */
  public static function checkRoles(array $roles): bool
  {
    if (empty($roles)) {
      return false;
    }

    $current_user = wp_get_current_user();
    $user_roles   = $current_user->roles ?? [];

    return !empty(array_intersect($user_roles, $roles));
  }

  /**
   * Check if the current admin page is in the allowed pages.
   *
   * @since 1.0.0
   * @param array $allowed_pages The allowed pages.
   */
  public static function isCurrentAdminPage(array $allowed_pages): bool
  {
    if (!is_admin()) {
      return false;
    }

    return in_array(self::getCurrentAdminPage(), $allowed_pages, true);
  }

  /**
   * Get the current admin page.
   *
   * We don't use get_current_screen() because it's not available in early hooks
   * like wp_theme_json_data_theme.
   *
   * @since 1.0.0
   */
  public static function getCurrentAdminPage(): string
  {
    global $pagenow;
    return $pagenow;
  }
}
