<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Analytics {

	public static function get_login_activity( $days = 14 ) {
		global $wpdb;

		$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT DATE(attempt_time) as date,
					SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
					SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success
				FROM {$wpdb->prefix}zacls_login_attempts
				WHERE attempt_time >= %s - INTERVAL %d DAY
				GROUP BY DATE(attempt_time)
				ORDER BY date ASC",
				current_time( 'mysql' ),
				$days
			),
			ARRAY_A
		);

		$chart = array();
		for ( $i = $days - 1; $i >= 0; $i-- ) {
			$date = gmdate( 'Y-m-d', strtotime( "-{$i} days" ) );
			$found = false;
			foreach ( $results as $row ) {
				if ( $row['date'] === $date ) {
					$chart[] = array(
						'date'    => $date,
						'failed'  => (int) $row['failed'],
						'success' => (int) $row['success'],
						'label'   => gmdate( 'M j', strtotime( $date ) ),
					);
					$found = true;
					break;
				}
			}
			if ( ! $found ) {
				$chart[] = array(
					'date'    => $date,
					'failed'  => 0,
					'success' => 0,
					'label'   => gmdate( 'M j', strtotime( $date ) ),
				);
			}
		}

		return $chart;
	}

	public static function get_browser_stats( $days = 30 ) {
		global $wpdb;

		$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT user_agent FROM {$wpdb->prefix}zacls_login_attempts
				WHERE attempt_time >= %s - INTERVAL %d DAY
				AND user_agent != ''",
				current_time( 'mysql' ),
				$days
			),
			ARRAY_A
		);

		$browsers = array();
		foreach ( $results as $row ) {
			$ua = $row['user_agent'];
			$browser = 'Unknown';
			if ( false !== strpos( $ua, 'Chrome' ) && false === strpos( $ua, 'Edg' ) ) {
				$browser = 'Chrome';
			} elseif ( false !== strpos( $ua, 'Firefox' ) ) {
				$browser = 'Firefox';
			} elseif ( false !== strpos( $ua, 'Safari' ) && false === strpos( $ua, 'Chrome' ) ) {
				$browser = 'Safari';
			} elseif ( false !== strpos( $ua, 'Edg' ) ) {
				$browser = 'Edge';
			} elseif ( false !== strpos( $ua, 'MSIE' ) || false !== strpos( $ua, 'Trident' ) ) {
				$browser = 'Internet Explorer';
			} elseif ( false !== strpos( $ua, 'Opera' ) || false !== strpos( $ua, 'OPR' ) ) {
				$browser = 'Opera';
			}
			if ( ! isset( $browsers[ $browser ] ) ) {
				$browsers[ $browser ] = 0;
			}
			$browsers[ $browser ]++;
		}

		arsort( $browsers );
		return $browsers;
	}

	public static function get_os_stats( $days = 30 ) {
		global $wpdb;

		$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT user_agent FROM {$wpdb->prefix}zacls_login_attempts
				WHERE attempt_time >= %s - INTERVAL %d DAY
				AND user_agent != ''",
				current_time( 'mysql' ),
				$days
			),
			ARRAY_A
		);

		$os_stats = array();
		foreach ( $results as $row ) {
			$ua = $row['user_agent'];
			$os = 'Unknown';
			if ( false !== strpos( $ua, 'Windows NT' ) ) {
				$os = 'Windows';
			} elseif ( false !== strpos( $ua, 'Mac OS X' ) ) {
				$os = 'macOS';
			} elseif ( false !== strpos( $ua, 'Linux' ) && false !== strpos( $ua, 'Android' ) ) {
				$os = 'Android';
			} elseif ( false !== strpos( $ua, 'Linux' ) ) {
				$os = 'Linux';
			} elseif ( false !== strpos( $ua, 'iPhone' ) || false !== strpos( $ua, 'iPad' ) ) {
				$os = 'iOS';
			} elseif ( false !== strpos( $ua, 'CrOS' ) ) {
				$os = 'Chrome OS';
			}
			if ( ! isset( $os_stats[ $os ] ) ) {
				$os_stats[ $os ] = 0;
			}
			$os_stats[ $os ]++;
		}

		arsort( $os_stats );
		return $os_stats;
	}

	public static function get_country_stats( $days = 30 ) {
		global $wpdb;

		$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"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",
				current_time( 'mysql' ),
				$days
			),
			ARRAY_A
		);

		return $results;
	}

	public static function get_attack_timeline( $hours = 24 ) {
		global $wpdb;

		$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT DATE_FORMAT(attempt_time, '%%Y-%%m-%%d %%H:00') as hour,
					COUNT(*) as total,
					SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
				FROM {$wpdb->prefix}zacls_login_attempts
				WHERE attempt_time >= %s - INTERVAL %d HOUR
				GROUP BY DATE_FORMAT(attempt_time, '%%Y-%%m-%%d %%H:00')
				ORDER BY hour ASC",
				current_time( 'mysql' ),
				$hours
			),
			ARRAY_A
		);

		return $results;
	}

	public static function get_top_attackers( $limit = 10, $days = 7 ) {
		global $wpdb;

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

		return $results;
	}

	public static function get_world_map_data( $days = 30 ) {
		global $wpdb;

		$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT country_code, COUNT(*) as attempts,
					SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
					SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success
				FROM {$wpdb->prefix}zacls_login_attempts
				WHERE attempt_time >= %s - INTERVAL %d DAY
				AND country_code != ''
				GROUP BY country_code
				ORDER BY attempts DESC",
				current_time( 'mysql' ),
				$days
			),
			ARRAY_A
		);

		return $results;
	}

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

		$failed  = ZACLS_Login_Limiter::get_total_attempts( 'failed', $days );
		$success = ZACLS_Login_Limiter::get_total_attempts( 'success', $days );
		$blocked = ZACLS_IP_Blocker::get_blocked_count();
		$twofa   = ZACLS_TwoFA::get_2fa_stats();

		$unique_ips = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT COUNT(DISTINCT ip) FROM {$wpdb->prefix}zacls_login_attempts
				WHERE attempt_time >= %s - INTERVAL %d DAY",
				current_time( 'mysql' ),
				$days
			)
		);

		$attack_rate = $failed + $success > 0
			? round( ( $failed / ( $failed + $success ) ) * 100, 1 )
			: 0;

		return array(
			'failed'        => $failed,
			'success'       => $success,
			'total'         => $failed + $success,
			'blocked'       => $blocked,
			'unique_ips'    => $unique_ips,
			'attack_rate'   => $attack_rate,
			'twofa_total'   => $twofa['total'] ?? 0,
			'twofa_enabled' => $twofa['enabled'] ?? 0,
		);
	}
}
