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

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

		$newmediaaddnotice = $schedules_interval->newmediaaddnotice ?? 'false';
		$mediadelete = $schedules_interval->mediadelete ?? 'false';
		$trackEmail = $schedules_interval->trackEmail ?? 'false';

		// Track media file added and send notice to admin.
		if ( true === $newmediaaddnotice ) {
			add_action('add_attachment', [ $this, 'wpnts_media_attachment_added' ]);
		}

		// Track media file deletion.
		if ( true === $mediadelete ) {
			add_action('delete_attachment', [ $this, 'wpnts_media_attachment_deleted' ]);
		}

		// Track email sending.
		if ( true === $trackEmail ) {
			add_filter('wp_mail', [ $this, 'wpnts_log_email_sent' ]);
			add_action('wp_mail_failed', [ $this, 'wpnts_log_email_failed' ]);
		}
	}

	/**
	 * Handles WordPress media file added notifications.
	 *
	 * This function triggers when a media file is added in WordPress. It sends a notification
	 * to Slack with details about the added file and logs the event with relevant information.
	 *
	 * @since 1.0.0
	 *
	 * @param int $attachment_id The ID of the added media attachment.
	 * @return void
	 */
	public function wpnts_media_attachment_added( $attachment_id ) {
		$attachment_title = get_the_title($attachment_id);
		$author = get_user_by('ID', get_post_field('post_author', $attachment_id))->display_name;

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

		$this->wpnts_notify_slack("New media file named '{$attachment_title}' uploaded by *{$author}*  $site_url", ':camera:');

		$log_message = "New media file named <b>'$attachment_title'</b> has been uploaded by 👉 <b>$author.</b>  <br>$site_url";
		$severity = 'High';
		$event_type = 'Media';
		$time = current_time( 'mysql' );

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

	/**
	 * Handles WordPress media file deletion notifications.
	 *
	 * This function triggers when a media file is deleted in WordPress. It sends a notification
	 * to Slack with details about the deleted file and logs the event with relevant information.
	 *
	 * @since 1.0.0
	 *
	 * @param int $attachment_id The ID of the deleted media attachment.
	 * @return void
	 */
	public function wpnts_media_attachment_deleted( $attachment_id ) {
		$attachment_title = get_the_title($attachment_id);
		$author = get_user_by('ID', get_post_field('post_author', $attachment_id))->display_name;

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

		$this->wpnts_notify_slack("Media file named '{$attachment_title}' deleted by *{$author}*  $site_url", ':wastebasket:');

		$log_message = "Media file named <b>'$attachment_title'</b> has been deleted by 👉 <b>$author.</b>  <br> $site_url";
		$severity = 'High';
		$event_type = 'Media';
		$time = current_time( 'mysql' );
		$ip = $attachmentHandler->get_user_ip();
		$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $author, $event_type, $log_message  );
	}


	/**
	 * Log successful email sends.
	 *
	 * @param array $args Email arguments.
	 * @return array Modified email arguments.
	 */
	public function wpnts_log_email_sent( $args ) {
		// Extract email details.
		$to      = is_array($args['to']) ? implode(', ', $args['to']) : $args['to'];
		$subject = $args['subject'];
		$message = $args['message'];
		$headers = $args['headers'];
		$attachments = $args['attachments'];

		// Get current user.
		$current_user = wp_get_current_user();
		$sender = $current_user->user_email ? $current_user->user_email : 'System';

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

		// Construct log message.
		$log_message = "Email sent from <b>'$sender'</b> to <b>'$to'</b><br>  $site_url";
		$log_message .= "<b>Subject:</b> $subject<br>";
		$log_message .= "<b>Message:</b> $message<br>";
		if ( ! empty($attachments) ) {
			$log_message .= '<b>Attachments:</b> ' . implode(', ', $attachments) . '<br>';
		}

		// Log the email event to the database.
		$severity = 'Medium';
		$event_type = 'Email';
		$time = current_time('mysql');

		// Get user's IP address
		$ip = $attachmentHandler->get_user_ip();
		// Log the activity to the database.
		$attachmentHandler->log_activity_to_db($severity, $time, $ip, $sender, $event_type, $log_message);

		// Optional: Notify via Slack.
		$this->wpnts_notify_slack("Email sent success from *{$sender}* to *{$to}*  $site_url", ':email:');

		// Return the original args to continue the email sending process.
		return $args;
	}


	/**
	 * Log failed email attempts.
	 *
	 * @param WP_Error $error Error object with details about the failure.
	 */
	public function wpnts_log_email_failed( $error ) {
		// Extract email details from the error data.
		$mail_data = $error->get_error_data();
		$to = is_array($mail_data['to']) ? implode(', ', $mail_data['to']) : $mail_data['to'];
		$subject = $mail_data['subject'];
		$message = $mail_data['message'];
		$headers = $mail_data['headers'];
		$attachments = isset($mail_data['attachments']) ? implode(', ', $mail_data['attachments']) : 'No Attachments';

		// Get current user.
		$current_user = wp_get_current_user();
		$sender = $current_user->user_email ? $current_user->user_email : 'System';

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

		// Extract error details.
		$error_message = $error->get_error_message();

		// Construct log message.
		$log_message = "Failed to send email from <b>'$sender'</b> to <b>'$to'</b><br>  $site_url";
		$log_message .= "<b>Subject:</b> $subject<br>";
		$log_message .= "<b>Message:</b> $message<br>";
		$log_message .= "<b>Headers:</b> " . (is_array($headers) ? implode(', ', $headers) : $headers) . "<br>";
		$log_message .= "<b>Attachments:</b> " . (is_array($attachments) ? implode(', ', $attachments) : $attachments) . "<br>";
		$log_message .= "<b>Error:</b> $error_message<br>";

		// Log the email event to the database.
		$severity = 'High'; // Marking email failures with a higher severity.
		$event_type = 'Email Failure';
		$time = current_time('mysql');

		// Get user's IP address.
		$ip = $attachmentHandler->get_user_ip();

		// Log the activity to the database.
		$attachmentHandler = new SlackAttachment();
		$attachmentHandler->log_activity_to_db($severity, $time, $ip, $sender, $event_type, $log_message);

		// Optional: Notify via Slack about the failure.
		$this->wpnts_notify_slack("Failed to send email  $site_url from *{$sender}* to *{$to}* with subject '{$subject}'. Error: {$error_message}", ':x:');
	}

	/**
	 * 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 media 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_media_settings',
			$formatted_message
		);
	}
}
