<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Performance {

	public static function get_stats() {
		global $wpdb;

		$memory_limit   = ini_get( 'memory_limit' );
		$memory_usage   = function_exists( 'memory_get_peak_usage' ) ? memory_get_peak_usage( true ) : 0;
		$memory_pct     = $memory_limit ? round( ( $memory_usage / self::let_to_num( $memory_limit ) ) * 100, 1 ) : 0;

		$db_size = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT SUM(data_length + index_length) FROM information_schema.tables WHERE table_schema = DATABASE()"
		);
		$total_tables = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()"
		);
		$plugin_tables = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
			"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name LIKE %s",
			$wpdb->prefix . 'zacls_%'
		) );

		$crons     = self::get_cron_stats();
		$db_queries = (int) $wpdb->num_queries;

		$login_log_count  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}zacls_login_attempts" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$audit_log_count  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}zacls_audit_log" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$blocked_count    = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}zacls_blocked_ips" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$risk_score_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}zacls_risk_scores" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$total_rows       = $login_log_count + $audit_log_count + $blocked_count + $risk_score_count;

		return array(
			'memory_limit'    => $memory_limit,
			'memory_usage'    => $memory_usage ? size_format( $memory_usage ) : 'N/A',
			'memory_pct'      => $memory_pct,
			'db_size'         => $db_size ? size_format( $db_size ) : 'N/A',
			'db_tables'       => $total_tables,
			'plugin_tables'   => $plugin_tables,
			'crons'           => $crons['count'],
			'overdue_crons'   => $crons['overdue'],
			'db_queries'      => $db_queries,
			'login_log_count' => $login_log_count,
			'audit_log_count' => $audit_log_count,
			'blocked_count'   => $blocked_count,
			'risk_scores'     => $risk_score_count,
			'total_db_rows'   => $total_rows,
		);
	}

	private static function get_cron_stats() {
		$cron      = _get_cron_array();
		$now       = time();
		$count     = 0;
		$overdue   = 0;

		if ( is_array( $cron ) ) {
			foreach ( $cron as $timestamp => $jobs ) {
				$count += count( $jobs );
				if ( $timestamp < $now ) {
					$overdue += count( $jobs );
				}
			}
		}

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

	private static function let_to_num( $size ) {
		$l   = substr( $size, -1 );
		$ret = (int) substr( $size, 0, -1 );
		switch ( strtoupper( $l ) ) {
			case 'P': $ret *= 1024;
			case 'T': $ret *= 1024;
			case 'G': $ret *= 1024;
			case 'M': $ret *= 1024;
			case 'K': $ret *= 1024;
		}
		return $ret;
	}

	public static function cleanup_old_data( $days = 90 ) {
		global $wpdb;

		$deleted_logs   = (int) $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}zacls_login_attempts WHERE attempt_time < %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );
		$deleted_audit  = (int) $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}zacls_audit_log WHERE created_at < %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );
		$deleted_scores = (int) $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}zacls_risk_scores WHERE created_at < %s - INTERVAL %d DAY",
			current_time( 'mysql' ), $days
		) );
		$deleted_blocked = (int) $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}zacls_blocked_ips WHERE blocked_at < %s - INTERVAL %d DAY AND type != 'manual'",
			current_time( 'mysql' ), $days
		) );

		ZACLS_Audit_Trail::log( 'auto_cleanup', sprintf(
			'Cleaned up data older than %d days: %d logs, %d audit, %d risk scores, %d blocked IPs',
			$days, $deleted_logs, $deleted_audit, $deleted_scores, $deleted_blocked
		) );

		return compact( 'deleted_logs', 'deleted_audit', 'deleted_scores', 'deleted_blocked' );
	}
}
