<?php
/**
 * Log Manager — FREE
 *
 * Tracks the last 50 settings changes (option key, timestamp, user ID).
 *
 * @package Panelra
 */

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

/**
 * Class Pnlrdb_Log_Manager
 */
class Pnlrdb_Log_Manager {

	/** Maximum number of log entries to keep. */
	const MAX = 50;

	/**
	 * Register hooks on the options that should be logged.
	 */
	public function __construct() {
		$tracked_options = array(
			'pnlrdb_menu_names',
			'pnlrdb_dashboard_colors',
			'pnlrdb_maintenance_enabled',
			'pnlrdb_hidden_dashboard_widgets',
			'pnlrdb_role_menu_visibility',
			'pnlrdb_hide_notices',
		);

		foreach ( $tracked_options as $opt ) {
			add_action( 'update_option_' . $opt, array( $this, 'log' ), 10, 2 );
		}

		/**
		 * Allows Pro (or other modules) to register additional options for logging.
		 *
		 * @param callable $callback  The log callback to attach to update_option_* hooks.
		 */
		do_action( 'pnlrdb_register_log_hooks', array( $this, 'log' ) );
	}

	/**
	 * Record a log entry when a tracked option changes.
	 *
	 * @param mixed $old_value Previous option value (unused).
	 * @param mixed $new_value New option value (unused).
	 * @return void
	 */
	public function log( $old_value, $new_value ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
		$option = str_replace( 'update_option_', '', current_filter() );
		$logs   = get_option( 'pnlrdb_logs', array() );

		array_unshift(
			$logs,
			array(
				'time'   => current_time( 'mysql' ),
				'option' => $option,
				'user'   => get_current_user_id(),
			)
		);

		update_option( 'pnlrdb_logs', array_slice( $logs, 0, self::MAX ) );
	}

	/**
	 * Retrieve all stored log entries.
	 *
	 * @return array
	 */
	public static function get_logs() {
		return get_option( 'pnlrdb_logs', array() );
	}

	/**
	 * Delete all stored log entries.
	 *
	 * @return void
	 */
	public static function clear_logs() {
		delete_option( 'pnlrdb_logs' );
	}
}
