<?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!');
/**
 * Postnotice used to rest route created.
 *
 * @since 1.0.0
 */
class Postnotice {

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

		$newpagecreate = $schedules_interval->newpagecreate ?? 'false';
		$deletepostnpage = $schedules_interval->deletepostnpage ?? 'false';

		// Track page and post creation and send notice to admin.
		if ( true === $newpagecreate ) {
			add_action('save_post', [ $this, 'wpnts_send_page_notification' ], 10, 3);
		}

		// Track page and post deletion and send notice to admin.
		if ( true === $deletepostnpage ) {
			add_action('before_delete_post', [ $this,'wpnts_send_post_deletion_notification' ]);
		}
	}


	/**
	 * 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 int    $post_ID The ID of the post being saved.
	 * @param object $post    The post object being saved.
	 * @param bool   $update  Whether this is an update or a new post.
	 * @return void
	 */
	public function wpnts_send_page_notification( $post_ID, $post, $update ) {
		if ( 'page' === $post->post_type ) {

			$post_status = get_post_status($post_ID);
			$author = get_user_by('ID', $post->post_author)->display_name;

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

			/**
			 * Plugin activity log.
			 */
			$severity = 'Medium';
			$event_type = 'Page';
			$time = current_time( 'mysql' );

			switch ( $post_status ) {
				case 'draft':
					$this->wpnts_notify_slack("Page named ➡️ '{$post->post_title}' saved as draft by {$author}  $site_url", ':pencil:');
					$log_message = "Page named ➡️ '{$post->post_title}' saved as <b>draft</b> by <b>$author</b> <br> $site_url";
					$ip = $attachmentHandler->get_user_ip();
					$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );

					break;
				case 'publish':
					$post_creation_time = strtotime($post->post_date);
					$current_time = current_time('timestamp', false);

					// Check if the post was recently updated (within the last minute).
					$is_recently_updated = ( $current_time > $post_creation_time );

					if ( $is_recently_updated ) {
						// Post modified.
						$this->wpnts_notify_slack("Page named ➡️ '{$post->post_title}' has been modified by {$author}  $site_url", ':pencil:');

						$log_message = "Page named ➡️ '{$post->post_title}' has been <b>modified</b> by <b>$author</b>  <br> $site_url";
						$ip = $attachmentHandler->get_user_ip();
						$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );

					} else {
						// Post published.
						$permalink = get_permalink($post_ID);
						$this->wpnts_notify_slack("Page named ➡️ '{$post->post_title}' has been published by {$author}.  $site_url | View page: {$permalink}", ':rocket:');

						$log_message = "Page named ➡️ '{$post->post_title}' has been <b>published</b> by <b>$author</b>  <br> $site_url | View page: {$permalink}";
						$ip = $attachmentHandler->get_user_ip();
						$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );

					}
					break;
				case 'private':
					$this->wpnts_notify_slack("Page named ➡️ '{$post->post_title}' has been marked as private by {$author}  $site_url", ':lock:');

					$log_message = "Page named ➡️ '{$post->post_title}' has been marked as <b>private</b> by <b>$author</b>  <br> $site_url";
					$ip = $attachmentHandler->get_user_ip();
					$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );
					break;
			}
		}
	}

	/**
	 * 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 int $post_ID The ID of the post being deleted.
	 * @return void
	 */
	public function wpnts_send_post_deletion_notification( $post_ID ) {

		$post = get_post($post_ID);

		/**
		 * Plugin activity log.
		 */
		$severity = 'Medium';
		$time = current_time( 'mysql' );

		if ( $post ) {
			$post_type = $post->post_type;
			$author = get_user_by('ID', $post->post_author)->display_name;

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

			if ( $post_type === 'page' ) {
				$this->wpnts_notify_slack("Page named :arrow_right: *{$post->post_title}* deleted by {$author}  $site_url", ':wastebasket:');
				$event_type = 'Page';
				$log_message = "Page named ➡️ '{$post->post_title}' has been deleted by <b>$author</b>  <br> $site_url";

				$ip = $attachmentHandler->get_user_ip();
				$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );

				return;
			} elseif ( $post_type === 'post' ) {
				$this->wpnts_notify_slack("Post named➡️ *{$post->post_title}* deleted by {$author}  $site_url", ':wastebasket:');
				$event_type = 'Post';
				$log_message = "Page named ➡️ '{$post->post_title}' has been deleted by <b>$author</b>  <br> $site_url";

				$ip = $attachmentHandler->get_user_ip();
				$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );

			}
		}
	}

	/**
	 * Sends a notification message to a configured Slack webhook with channel routing.
	 *
	 * This function formats a message with an optional emoji and sends it to the Slack webhook URL
	 * specified in the plugin's page/post settings, with support for custom channels and user tags.
	 *
	 * @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_pagenpost_settings',
			$formatted_message
		);
	}
}
