<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_AI_Assistant {

	public static function get_briefing( $days = 1 ) {
		global $wpdb;

		$total  = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM {$wpdb->prefix}zacls_login_attempts WHERE attempt_time >= %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );
		$failed = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM {$wpdb->prefix}zacls_login_attempts WHERE status = 'failed' AND attempt_time >= %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );
		$blocked = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM {$wpdb->prefix}zacls_blocked_ips WHERE blocked_at >= %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );
		$success = $total - $failed;

		$countries = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT country_code, COUNT(*) as cnt FROM {$wpdb->prefix}zacls_login_attempts
			WHERE attempt_time >= %s - INTERVAL %d DAY AND country_code != ''
			GROUP BY country_code ORDER BY cnt DESC LIMIT 5",
			current_time( 'mysql' ), $days
		), ARRAY_A );

		$top_username = $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT username FROM {$wpdb->prefix}zacls_login_attempts
			WHERE status = 'failed' AND attempt_time >= %s - INTERVAL %d DAY
			GROUP BY username ORDER BY COUNT(*) DESC LIMIT 1",
			current_time( 'mysql' ), $days
		) );

		$new_ips_blocked = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM {$wpdb->prefix}zacls_blocked_ips
			WHERE blocked_at >= %s - INTERVAL %d DAY AND type = 'auto'",
			current_time( 'mysql' ), $days
		) );

		$recent_2fa_failures = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM {$wpdb->prefix}zacls_audit_log
			WHERE action LIKE '%%2fa%%' AND details LIKE '%%fail%%'
			AND created_at >= %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );

		$country_lines = array();
		foreach ( $countries as $c ) {
			$country_lines[] = sprintf( '%d from %s', $c['cnt'], $c['country_code'] ?: 'Unknown' );
		}

		$lines = array();

		if ( $total > 0 ) {
			$lines[] = sprintf(
				'You had %d login attempt%s in the last %s.',
				$total,
				$total !== 1 ? 's' : '',
				$days === 1 ? '24 hours' : sprintf( '%d days', $days )
			);
			$lines[] = sprintf( '%d blocked, %d failed, %d successful.', $blocked, $failed, $success );
			if ( ! empty( $country_lines ) ) {
				$lines[] = 'Top countries: ' . implode( ', ', $country_lines ) . '.';
			}
			if ( $top_username ) {
				$lines[] = sprintf( 'Most attacked username: "%s".', $top_username );
			}
			if ( $new_ips_blocked > 0 ) {
				$lines[] = sprintf( '%d new IP%s automatically blocked.', $new_ips_blocked, $new_ips_blocked !== 1 ? 's' : '' );
			}
			if ( $recent_2fa_failures > 0 ) {
				$lines[] = sprintf( '%d 2FA verification failure%s detected.', $recent_2fa_failures, $recent_2fa_failures !== 1 ? 's' : '' );
			}
		} else {
			$lines[] = 'No login activity detected in the last ' . ( $days === 1 ? '24 hours' : sprintf( '%d days', $days ) ) . '.';
			$lines[] = 'Your site is currently quiet.';
		}

		$recommendations = self::get_recommendations( $total, $failed, $blocked, $countries );

		return array(
			'summary'        => implode( "\n", $lines ),
			'stats'          => compact( 'total', 'failed', 'success', 'blocked', 'new_ips_blocked', 'recent_2fa_failures' ),
			'countries'      => $countries,
			'top_username'   => $top_username,
			'recommendations'=> $recommendations,
		);
	}

	private static function get_recommendations( $total, $failed, $blocked, $countries ) {
		$recs = array();

		if ( $failed > 50 ) {
			$recs[] = array(
				'icon'  => 'dashicons-warning',
				'text'  => 'High failed login volume detected. Consider enabling or tightening rate limiting.',
				'tab'   => 'settings',
				'type'  => 'warning',
			);
		}

		if ( $blocked > 20 ) {
			$recs[] = array(
				'icon'  => 'dashicons-shield',
				'text'  => 'Many IPs are being blocked automatically. Review blocked IPs for patterns.',
				'tab'   => 'blocked-ips',
				'type'  => 'info',
			);
		}

		foreach ( $countries as $c ) {
			if ( ! empty( $c['country_code'] ) && $c['cnt'] > 10 && ! in_array( $c['country_code'], array( 'US', 'GB', 'CA', 'AU', 'ZA' ), true ) ) {
				$recs[] = array(
					'icon'  => 'dashicons-location',
					'text'  => sprintf( 'Suspicious activity from %s (%d attempts). Consider enabling Geo Blocking.', $c['country_code'], $c['cnt'] ),
					'tab'   => 'settings',
					'type'  => 'warning',
				);
				break;
			}
		}

		if ( 'no' === get_option( 'zacls_geoip_enabled', 'no' ) ) {
			$recs[] = array(
				'icon'  => 'dashicons-location',
				'text'  => 'Enable GeoIP tracking to detect suspicious geographic login origins.',
				'tab'   => 'settings',
				'type'  => 'info',
			);
		}

		if ( 'yes' !== get_option( 'zacls_2fa_enabled', 'no' ) ) {
			$recs[] = array(
				'icon'  => 'dashicons-lock',
				'text'  => 'Enable Two-Factor Authentication to add an extra layer of security.',
				'tab'   => 'settings',
				'type'  => 'warning',
			);
		}

		return $recs;
	}
}
