<?php
/**
 * Lightweight audit trail for wp-config and debug configuration changes.
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

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

final class WpConfigAuditLog {

	private const TABLE = 'wpps_activity_log';

	/**
	 * Record a configuration action (never includes secret values).
	 */
	public static function log( string $module_id, string $action, string $description ): void {
		$module_id   = sanitize_key( $module_id );
		$action      = sanitize_key( $action );
		$description = sanitize_textarea_field( $description );
		$user_id     = get_current_user_id();

		/**
		 * Fires when a wp-config or debug configuration action is performed.
		 *
		 * @param string $module_id   Module identifier.
		 * @param string $action      Action slug.
		 * @param string $description Human-readable summary without secrets.
		 * @param int    $user_id     Acting user ID.
		 */
		do_action( 'wp_powersuite_wp_config_audit', $module_id, $action, $description, $user_id );

		if ( ! OptionStoreModuleSettingsRepository::isModuleEnabled( 'advanced-user-activity-log' ) ) {
			return;
		}

		global $wpdb;
		$table = $wpdb->prefix . self::TABLE;
		$exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
		if ( $exists !== $table ) {
			return;
		}

		$user       = $user_id ? get_userdata( $user_id ) : false;
		$user_login = $user instanceof \WP_User ? $user->user_login : null;
		$ip_address = self::clientIp();

		$wpdb->insert(
			$table,
			[
				'user_id'     => $user_id ?: null,
				'user_login'  => $user_login,
				'action'      => 'wpps_' . $module_id . '_' . $action,
				'object_type' => 'wp_config',
				'object_id'   => null,
				'object_name' => $module_id,
				'description' => $description,
				'ip_address'  => $ip_address,
				'user_agent'  => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : null,
				'created_at'  => current_time( 'mysql' ),
			],
			[ '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' ]
		);
	}

	private static function clientIp(): string {
		if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
			return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
		}

		return '0.0.0.0';
	}
}
