<?php
/**
 * Activity Guard – Real Time Notifier to Slack Rest Route.
 *
 * This class is used to response and all rest route works.
 *
 * @package WPNTS\Inc
 */

namespace WPNTS\Inc;

use WPNTS\Inc\wpnts_nts_fs; // phpcs:ignore
use WPNTS\Inc\Activate; // phpcs:ignore
use WPNTS\Inc\Deactivate; // phpcs:ignore
use WPNTS\Inc\Database\DB; // phpcs:ignore
use WPNTS\Inc\SlackAttachment; // phpcs:ignore
use WPNTS\Inc\SlackChannelRouter; // phpcs:ignore

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');
/**
 * Wpwidgets used to rest route created.
 *
 * @since 1.0.0
 */
class Wpwidgets {

	/**
	 * Construct method.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$wpnts_db_instance = new DB();
		$schedules_int = get_option( 'wpntswebhook_widget_settings');
		$schedules_interval = json_decode($schedules_int);

		$save_widget = $schedules_interval->save_widget ?? 'false';
		$delete_widget = $schedules_interval->delete_widget ?? 'false';

		// Track widget save/update.
		if ( true === $save_widget ) {
			add_action('widget_update_callback', [ $this, 'wpnts_widget_updated' ], 10, 3);
			add_action('wp_ajax_widgets-order', [ $this, 'wpnts_widget_added' ]);
		}

		// Track widget delete.
		// Check if the delete_widget option is set to true.
		if ( true === $delete_widget ) {
			add_action('wp_ajax_delete_widget', [ $this, 'wpnts_hook_widget_delete' ]);
		}
	}


	/**
	 * Handle WordPress widget update notifications.
	 *
	 * This function sends a Slack notification and logs an entry when a widget is updated in WordPress.
	 * It includes details of the updated widget and the user who made the update.
	 *
	 * @since 1.0.0
	 * @param WP_Widget $instance The current widget instance.
	 * @param array     $new_instance The new widget settings.
	 * @param array     $old_instance The old widget settings.
	 * @return WP_Widget The updated widget instance.
	 */
	public function wpnts_widget_updated( $instance, $new_instance, $old_instance ) {
		$widget_id = sanitize_text_field($instance->id_base);
		// Get the current user's details.
		$user_id = get_current_user_id();
		$author = get_the_author_meta('display_name', $user_id);

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$this->wpnts_notify_slack("Widget '{$widget_id}' updated by '{$author}'.  $site_url", ':package:');

		$log_message = "Widget <b>'$widget_id'</b> updated by <b>$author</b>.  <br> $site_url";
		$this->log_to_db($log_message, 'Widget', 'High', $author);

		return $instance;
	}


	/**
	 * Notify when a WordPress widget is added.
	 *
	 * This function sends a Slack notification and logs an entry when a widget is added to the WordPress site.
	 * It includes details of the added widget and the user who performed the action.
	 *
	 * @since 1.0.0
	 */
	public function wpnts_widget_added() {
		$user_id = get_current_user_id();
		$author = get_the_author_meta('display_name', $user_id);

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$this->wpnts_notify_slack("New Widget added by '{$author}'.  $site_url", ':package:');

		$log_message = "New Widget added by <b>$author</b>.  <br> $site_url";
		$this->log_to_db($log_message, 'Widget', 'High', $author);
	}

	/**
	 * Notify when a WordPress widget is deleted.
	 *
	 * This function sends a Slack notification and logs an entry when a widget is deleted from the WordPress site.
	 * It includes details of the deleted widget and the user who performed the action.
	 *
	 * @since 1.0.0
	 */
	public function wpnts_hook_widget_delete() {
		check_ajax_referer('delete-widget', 'nonce');
		$widget_id = isset( $_POST['widget-id'] ) ? sanitize_text_field( wp_unslash( $_POST['widget-id'] ) ) : '';
		// Get the current user's details.
		$user_id = get_current_user_id();

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$author = get_the_author_meta('display_name', $user_id);

		$this->wpnts_notify_slack("Widget '{$widget_id}' removed by '{$author}'.  $site_url", ':package:');

		$log_message = "Widget <b>'$widget_id'</b> removed by <b>$author</b>.  <br> $site_url";
		$this->log_to_db($log_message, 'Widget', 'High', $author);
	}

	/**
	 * Log activity to the database.
	 *
	 * This helper function logs user activity to the database, including the IP address of the user,
	 * severity of the event, time, and the author who performed the action.
	 *
	 * @since 1.0.0
	 * @param string $message The message describing the activity being logged.
	 * @param string $event_type The type of event (e.g., "Widget").
	 * @param string $severity The severity level of the event (e.g., "High").
	 * @param string $author The name of the user who performed the action.
	 */
	private function log_to_db( $message, $event_type, $severity, $author ) {
		$time = current_time('mysql');

		// Get IP Address.
		$attachmentHandler = new SlackAttachment();
		$ip = $attachmentHandler->get_user_ip();

		// Log activity to the database.
		$attachmentHandler->log_activity_to_db($severity, $time, $ip, $author, $event_type, $message);
	}


	/**
	 * Sends a notification message to a configured Slack webhook.
	 *
	 * This function formats a message with an optional emoji and sends it to the Slack webhook URL.
	 * specified in the plugin's comment settings.
	 *
	 * @param string $message The message to send to Slack.
	 * @param string $emoji   An optional emoji to prepend to the message.
	 * @return void
	 */
	private function wpnts_notify_slack( $message, $emoji = '' ) {
		$formatted_message = $emoji . ' ' . $message;
		
		// Use SlackChannelRouter for channel and user tag support
		SlackChannelRouter::send_notification_with_routing(
			'wpntswebhook_widget_settings',
			$formatted_message
		);
	}
}
