<?php

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

class AVIN_Bot_Filter {
	private $patterns = array(
		'bot',
		'crawler',
		'spider',
		'slurp',
		'curl',
		'wget',
		'python-requests',
		'httpclient',
		'googlebot',
		'bingbot',
		'duckduckbot',
		'yandex',
		'baiduspider',
		'ahrefs',
		'semrush',
		'mj12bot',
		'dotbot',
		'petalbot',
		'gptbot',
		'claudebot',
		'ccbot',
		'facebookexternalhit',
		'linkedinbot',
		'pinterestbot',
	);

	public function is_bot( $user_agent = null ) {
		if ( '1' !== (string) get_option( 'avin_bot_filtering', '1' ) ) {
			return false;
		}

		$user_agent = null === $user_agent ? ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) : '' ) : $user_agent; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$user_agent = strtolower( sanitize_text_field( (string) $user_agent ) );

		if ( '' === $user_agent ) {
			return true;
		}

		foreach ( $this->patterns as $pattern ) {
			if ( false !== strpos( $user_agent, $pattern ) ) {
				return (bool) apply_filters( 'avin_is_bot', true, $user_agent, $pattern );
			}
		}

		return (bool) apply_filters( 'avin_is_bot', false, $user_agent, '' );
	}
}
