<?php
/**
 * AI Visibility - Crawler Logging
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\AiVisibility;

/**
 * Handles crawler logging
 */
class CrawlerLogs {

	/**
	 * Maximum number of logs to keep
	 */
	const MAX_LOGS = 1000;

	/**
	 * Initialize crawler logging
	 */
	public static function init() {
		// Logging is passive - logs are added via API
	}

	/**
	 * Get crawler logs status
	 *
	 * @return array
	 */
	public static function get_status() {
		$enabled = \SEOvaultSEO\Core\Options::is_crawler_logging_enabled();
		$logs    = \SEOvaultSEO\Core\Options::get_crawler_logs();

		return array(
			'enabled' => $enabled,
			'count'   => count( $logs ),
		);
	}

	/**
	 * Enable crawler logging
	 *
	 * @return array
	 */
	public static function enable() {
		\SEOvaultSEO\Core\Options::set_crawler_logging_enabled( true );

		return array(
			'success' => true,
			'message' => 'Crawler logging enabled',
		);
	}

	/**
	 * Disable crawler logging
	 *
	 * @return array
	 */
	public static function disable() {
		\SEOvaultSEO\Core\Options::set_crawler_logging_enabled( false );

		return array(
			'success' => true,
			'message' => 'Crawler logging disabled',
		);
	}

	/**
	 * Get crawler logs
	 *
	 * @param int $limit Number of logs to return
	 * @param int $offset Offset for pagination
	 * @return array
	 */
	public static function get_logs( $limit = 100, $offset = 0 ) {
		$logs = \SEOvaultSEO\Core\Options::get_crawler_logs();

		// Reverse to show newest first
		$logs = array_reverse( $logs );

		// Apply pagination
		$logs = array_slice( $logs, $offset, $limit );

		return array(
			'success' => true,
			'data'    => $logs,
			'total'   => count( \SEOvaultSEO\Core\Options::get_crawler_logs() ),
		);
	}

	/**
	 * Add a crawler log entry
	 *
	 * Raw IP and User-Agent are hashed before storage (SHA-256), matching
	 * AuditLog privacy handling. The detected crawler label is derived from
	 * the raw UA first, then only the hash is persisted.
	 *
	 * @param array $log_data Log data
	 * @return bool
	 */
	public static function add_log( $log_data ) {
		if ( ! \SEOvaultSEO\Core\Options::is_crawler_logging_enabled() ) {
			return false;
		}

		if ( ! is_array( $log_data ) ) {
			$log_data = array();
		}

		$raw_ua = isset( $log_data['user_agent'] ) ? (string) $log_data['user_agent'] : '';
		$raw_ip = isset( $log_data['ip'] ) ? (string) $log_data['ip'] : '';

		$logs = \SEOvaultSEO\Core\Options::get_crawler_logs();

		$log_entry = array(
			'timestamp'  => current_time( 'mysql' ),
			'user_agent' => \SEOvaultSEO\Api\AuditLog::hash_user_agent( $raw_ua ),
			'ip'         => \SEOvaultSEO\Api\AuditLog::hash_ip( $raw_ip ),
			'url'        => $log_data['url'] ?? '',
			'method'     => $log_data['method'] ?? 'GET',
			'crawler'    => self::detect_crawler( $raw_ua ),
		);

		$logs[] = $log_entry;

		// Trim to max logs
		if ( count( $logs ) > self::MAX_LOGS ) {
			$logs = array_slice( $logs, -self::MAX_LOGS );
		}

		\SEOvaultSEO\Core\Options::set_crawler_logs( $logs );

		return true;
	}

	/**
	 * Detect crawler from user agent
	 *
	 * @param string $user_agent User agent string
	 * @return string
	 */
	private static function detect_crawler( $user_agent ) {
		$user_agent = strtolower( $user_agent );

		$crawlers = array(
			'googlebot'           => 'Google',
			'bingbot'             => 'Bing',
			'slurp'               => 'Yahoo',
			'duckduckbot'         => 'DuckDuckGo',
			'baiduspider'         => 'Baidu',
			'yandexbot'           => 'Yandex',
			'facebookexternalhit' => 'Facebook',
			'twitterbot'          => 'Twitter',
			'linkedinbot'         => 'LinkedIn',
			'pinterest'           => 'Pinterest',
			'applebot'            => 'Apple',
			'semrushbot'          => 'SEMrush',
			'ahrefsbot'           => 'Ahrefs',
			'mj12bot'             => 'Majestic',
		);

		foreach ( $crawlers as $pattern => $name ) {
			if ( strpos( $user_agent, $pattern ) !== false ) {
				return $name;
			}
		}

		return 'Unknown';
	}

	/**
	 * Clear all crawler logs
	 *
	 * @return array
	 */
	public static function clear_logs() {
		\SEOvaultSEO\Core\Options::set_crawler_logs( array() );

		return array(
			'success' => true,
			'message' => 'Crawler logs cleared',
		);
	}
}
