<?php
/**
 * Pro: device-type rule gating.
 *
 * @package EasySearchReplace
 */

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

/**
 * Detect device type from user agent and gate rules accordingly.
 *
 * We classify in three buckets:
 *   - tablet  : UA contains "tablet" or "ipad"
 *   - mobile  : wp_is_mobile() true AND not tablet
 *   - desktop : everything else
 *
 * Not perfect - UA sniffing never is - but good enough for broad
 * targeting. The main weakness is Android tablets that often report
 * themselves as mobile; we side on treating them as mobile unless the UA
 * says "tablet".
 */
class ESRN_Pro_Device {

	public static function register() {
		add_filter( 'esrn_should_apply_rule', array( __CLASS__, 'check' ), 10, 3 );
	}

	/**
	 * @param bool  $apply
	 * @param array $rule
	 * @param array $context
	 * @return bool
	 */
	public static function check( $apply, $rule, $context ) {
		if ( ! $apply ) {
			return false;
		}

		$required = isset( $rule['device'] ) ? (string) $rule['device'] : 'any';
		if ( 'any' === $required ) {
			return true;
		}

		$current = self::detect();
		return $current === $required;
	}

	/**
	 * Detect the device bucket for the current request.
	 *
	 * @return string 'desktop' | 'mobile' | 'tablet'
	 */
	public static function detect() {
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- UA is read-only string match.
		$ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
		$ua = strtolower( $ua );

		$is_tablet = ( false !== strpos( $ua, 'tablet' ) || false !== strpos( $ua, 'ipad' ) );
		if ( $is_tablet ) {
			return 'tablet';
		}

		if ( function_exists( 'wp_is_mobile' ) && wp_is_mobile() ) {
			return 'mobile';
		}

		return 'desktop';
	}
}
