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

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

		$wpnts_stockoutofstocknotifications = $schedules_interval->stockoutofstocknotifications ?? 'false';

		$wpntspro_salesnotifications = $schedules_interval->salesnotifications ?? 'false';
		$wooproducteditornotify = $schedules_interval->wooproducteditornotify ?? 'false';
		$shipingstatus = $schedules_interval->shipingstatus ?? 'false';
		$billingshippingnotify = $schedules_interval->billingshippingnotify ?? 'false';
		$incompleteordersnotifications = $schedules_interval->incompleteordersnotifications ?? 'false';

		// Product quantity status stock, out of stock Notifications to Slack.
		if ( true === $wpnts_stockoutofstocknotifications ) {
			add_action( 'woocommerce_product_set_stock', [ $this, 'wpnts_product_stock_notification' ], 10, 2 );
		}

		// This will send a notification when the order status changes.
		if ( true === $wpntspro_salesnotifications ) {
			add_action( 'woocommerce_order_status_changed', [ $this, 'sales_notification' ], 10, 4 );
		}
		// Use to simply send notice and Notify on product changes.
		if ( true === $wooproducteditornotify ) {
			add_action('save_post', [ $this, 'notify_on_product_changes' ], 10, 3);
		}
		// Use to simply send notice and Notify on shipping status updates.
		if ( true === $shipingstatus ) {
			add_action('woocommerce_order_status_changed', [ $this, 'notify_on_shipping_status_update' ], 10, 4);
		}
		// Use to simply send notice and notify on billing and shipping address updates.
		if ( true === $billingshippingnotify ) {
			add_action('woocommerce_saved_order_items', [ $this, 'notify_on_address_update' ], 10, 2);
		}
		// Incomplete orders tracking
		if ( true === $incompleteordersnotifications ) {
			add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_checkout_tracking_script' ] );
			add_action( 'woocommerce_checkout_order_processed', [ $this, 'mark_order_complete' ], 10, 3 );
			add_action( 'woocommerce_store_api_checkout_order_processed', [ $this, 'mark_order_complete_block' ], 10, 1 );
			add_action( 'wpnts_send_incomplete_order_notification', [ $this, 'send_scheduled_incomplete_order_notification' ] );
		}

		// Cart abandonment tracking (works even if incomplete orders is disabled)
		$cart_abandonment_tracking = $schedules_interval->cart_abandonment_tracking ?? true;
		if ( true === $cart_abandonment_tracking ) {
			add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_cart_session_tracking_script' ] );
		}
	}



	/**
	 * Send a stock notification to Slack when a product's stock status changes.
	 *
	 * @since 1.0.0
	 * @param int $product_id The ID of the product.
	 */
	public function wpnts_product_stock_notification( $product_id ) {
		$product = wc_get_product( $product_id );
		$stock = $product->get_stock_quantity();

		$schedules_int = get_option( 'wpnts_schedules_interval_woocommerce_settings');
		$schedules_interval = json_decode($schedules_int);
		$slack_webhook_url = $schedules_interval->webhook ?? '';

		// Initialize attachment handler for reusable functions
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		// Build message based on stock status
		$message = '';
		if ( $stock <= 0 ) {
			$message = "Product '" . $product->get_name() . "' is out of stock. $site_url";
		} else {
			$message = 'Product ' . $product->get_name() . ' is now back in stock with ' . $stock . ' items available. ' . $site_url;
		}

		// Send notification and log activity using reusable function with channel routing
		$attachmentHandler->send_notification_and_log( 
			$slack_webhook_url, 
			$message, 
			'High', 
			'WooCommerce Stock',
			'',
			[],
			'wpnts_schedules_interval_woocommerce_settings'
		);
	}


	/**
	 * Send a sales notification to Slack when an order status is updated.
	 *
	 * @since 1.0.0
	 * @param int      $order_id The ID of the order.
	 * @param string   $old_status The previous status of the order.
	 * @param string   $new_status The new status of the order.
	 * @param WC_Order $order The order object.
	 */
	public function sales_notification( $order_id, $old_status, $new_status, $order ) {
		$schedules_int = get_option( 'wpnts_schedules_interval_woocommerce_settings');
		$schedules_interval = json_decode($schedules_int);
		$slack_webhook_url = $schedules_interval->webhook ?? '';

		// Initialize attachment handler for reusable functions
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$user = $order->get_user();
		$username = $user ? $user->display_name : 'Guest';

		// Build comprehensive order message
		$message = 'Order #' . $order_id . ' has been updated from ' . $old_status . ' to ' . $new_status . ' for customer ' . $username . "\n  $site_url";

		foreach ( $order->get_items() as $item_id => $item ) {
			$product = $item->get_product();
			$product_name = $product->get_name();
			$product_price = $product->get_price();
			$product_quantity = $item->get_quantity();
			$product_total = $product_price * $product_quantity;

			$message .= "\nProduct: " . $product_name . "\nQuantity: " . $product_quantity . "\nPrice: $" . $product_price . "\nTotal: $" . $product_total;
		}

		$message .= "\n\nTotal Sales: $" . $order->get_total() . "\nOrder Number: " . $order_id;

		// Send notification and log activity using reusable function with channel routing
		$attachmentHandler->send_notification_and_log( 
			$slack_webhook_url, 
			$message, 
			'Medium', 
			'WooCommerce Sales',
			$username,
			[],
			'wpnts_schedules_interval_woocommerce_settings'
		);
	}



	/**
	 * Notify when a product is edited in WooCommerce.
	 *
	 * @since 1.0.0
	 * @param int        $product_id The ID of the product being edited.
	 * @param WC_Product $product The product object being edited.
	 * @param bool       $update Whether the product is being updated or created.
	 */
	public function notify_on_product_changes( $product_id, $product, $update ) {

		if ( is_a($product, 'WP_Post') && $product->post_type === 'product' ) {
			// Get the product object.
			$product_object = wc_get_product($product_id);

			// Log message for product changes.
			$log_message = $this->get_product_changes_message($product_object);

			$schedules_int = get_option('wpnts_schedules_interval_woocommerce_settings');
			$schedules_interval = json_decode($schedules_int);
			$wpntspro_webhook = $schedules_interval->webhook;

			// Send the notification to Slack if there are changes.
			if ( ! empty($log_message) ) {
				$attachmentHandler = new SlackAttachment();
				
				// Send notification and log activity using reusable function with channel routing
				$attachmentHandler->send_notification_and_log( 
					$wpntspro_webhook, 
					$log_message, 
					'Medium', 
					'Product Edit',
					'',
					[],
					'wpnts_schedules_interval_woocommerce_settings'
				);
			}
		}
	}

	/**
	 * Get the log message for changes made to a product.
	 *
	 * @since 1.0.0
	 * @param WC_Product $product_data The product object containing updated data.
	 * @return string The formatted log message detailing the product changes.
	 */
	private function get_product_changes_message( $product_data ) {
		$changes = [];

		// Check for changes in product title.
		if ( $product_data->get_name() ) {
			$changes[] = [
				'Field' => 'Product title',
				'Data' => $product_data->get_name(),
			];
		}

		// Check for changes in product short description.
		if ( $product_data->get_short_description() ) {
			$changes[] = [
				'Field' => 'Short description',
				'Data' => $product_data->get_short_description(),
			];
		}

		// Check for changes in product description.
		if ( $product_data->get_description() ) {
			$changes[] = [
				'Field' => 'Description',
				'Data' => $product_data->get_description(),
			];
		}

		// Check for changes in product SKU.
		if ( $product_data->get_sku() ) {
			$changes[] = [
				'Field' => 'SKU',
				'Data' => $product_data->get_sku(),
			];
		}

		// Check for changes in product stock.
		if ( $product_data->get_stock_quantity() ) {
			$changes[] = [
				'Field' => 'Stock',
				'Data' => $product_data->get_stock_quantity(),
			];
		}

		// Check for changes in product weight.
		if ( $product_data->get_weight() ) {
			$changes[] = [
				'Field' => 'Weight',
				'Data' => $product_data->get_weight(),
			];
		}

		// Check for changes in product regular price.
		if ( $product_data->get_regular_price() ) {
			$changes[] = [
				'Field' => 'Regular Price',
				'Data' => $product_data->get_regular_price(),
			];
		}

		// Check for changes in product sale price.
		if ( $product_data->get_sale_price() ) {
			$changes[] = [
				'Field' => 'Sale Price',
				'Data' => $product_data->get_sale_price(),
			];
		}

		// Check for changes in product image.
		if ( $product_data->get_image_id() ) {
			$image = wp_get_attachment_image_src($product_data->get_image_id(), 'full');
			$changes[] = [
				'Field' => 'Product Image',
				'Data' => $image[0],
			];
		}

		// Check for changes in product gallery.
		$gallery_image_ids = $product_data->get_gallery_image_ids();
		if ( ! empty($gallery_image_ids) ) {
			$gallery_images = [];
			foreach ( $gallery_image_ids as $gallery_image_id ) {
				$gallery_image = wp_get_attachment_image_src($gallery_image_id, 'full');
				$gallery_images[] = $gallery_image[0];
			}
			$changes[] = [
				'Field' => 'Product Gallery',
				'Data' => implode(', ', $gallery_images),
			];
		}

		// Check for changes in product type (Simple or Variable).
		$changes[] = [
			'Field' => 'Product Type',
			'Data' => $product_data->get_type(),
		];

		// Check for changes in stock status.
		$changes[] = [
			'Field' => 'Stock Status',
			'Data' => $product_data->get_stock_status(),
		];

		// Check for changes in product categories.
		$categories = implode(', ', wp_get_post_terms($product_data->get_id(), 'product_cat', [ 'fields' => 'names' ]));
		$changes[] = [
			'Field' => 'Product Categories',
			'Data' => $categories,
		];

		// Check for changes in product tags.
		$tags = implode(', ', wp_get_post_terms($product_data->get_id(), 'product_tag', [ 'fields' => 'names' ]));
		$changes[] = [
			'Field' => 'Product Tags',
			'Data' => $tags,
		];

		// Check for changes in product gallery (with clickable links).
		$gallery_images = [];
		foreach ( $gallery_image_ids as $gallery_image_id ) {
			$gallery_image = wp_get_attachment_image_src($gallery_image_id, 'full');
			$gallery_images[] = '<a href="' . esc_url($gallery_image[0]) . '">Click to view</a>';
		}
		$changes[] = [
			'Field' => 'Product Gallery',
			'Data' => implode(', ', $gallery_images),
		];

		// Format changes into a table.
		$table = "Listed product data has been updated\n<br>";
		$table .= "------------------------------------------------------\n<br>";

		foreach ( $changes as $change ) {
			$table .= sprintf("%s => %s \n", $change['Field'], $change['Data']);
		}

		return $table;
	}


	/**
	 * Notify on shipping status updates for an order.
	 *
	 * @since 1.0.0
	 * @param int      $order_id The ID of the order.
	 * @param string   $old_status The previous shipping status of the order.
	 * @param string   $new_status The new shipping status of the order.
	 * @param WC_Order $order The order object.
	 */
	public function notify_on_shipping_status_update( $order_id, $old_status, $new_status, $order ) {
		if ( $old_status !== $new_status ) {
			// Get the order data.
			$order_data = wc_get_order($order_id);

			// Log message for shipping status update.
			$log_message = $this->get_shipping_status_update_message($order_data);

			// Send the notification to Slack if there are changes.
			if ( ! empty($log_message) ) {
				$this->send_slack_notification($log_message);

				$activated_by = wp_get_current_user()->display_name;
				$severity = 'Medium';
				$event_type = 'Shiping';
				$time = current_time( 'mysql' );

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

			}
		}
	}

	/**
	 * Get the formatted message for a shipping status update.
	 *
	 * This function checks for changes in the shipping status of an order and returns a formatted message for the update.
	 *
	 * @since 1.0.0
	 * @param WC_Order $order_data The order object containing the shipping status.
	 * @return string The formatted message with the shipping status change details.
	 */
	private function get_shipping_status_update_message( $order_data ) {
		// Check for changes in shipping status.
		$changes = [];

		// Example: Check for changes in order shipping status.
		$changes[] = [
			'Field' => 'Shipping Status',
			'Data' => $order_data->get_status(),
		];

		// Format changes into a table.
		$table = "Shipping status has been updated\n<br>";
		$table .= "------------------------------------------------------\n<br>";

		foreach ( $changes as $change ) {
			$table .= sprintf(" %s => %s \n", $change['Field'], $change['Data']);
		}

		return $table;
	}


	/**
	 * Notify when the billing or shipping address is updated.
	 *
	 * This function compares the old and new billing and shipping addresses of an order. If any of the addresses have changed,
	 * it sends a notification to Slack and logs the activity.
	 *
	 * @since 1.0.0
	 * @param int   $order_id The ID of the order being updated.
	 * @param array $args The new address data to compare with the existing ones.
	 */
	public function notify_on_address_update( $order_id, $args ) {
		// Get the order object.
		$order = wc_get_order($order_id);

		// Check if the billing or shipping address has changed.
		$old_billing_address = $this->get_formatted_billing_address($order);
		$new_billing_address = $this->get_formatted_address_from_args($args, 'billing');

		$old_shipping_address = $this->get_formatted_shipping_address($order);
		$new_shipping_address = $this->get_formatted_address_from_args($args, 'shipping');

		$log_messages = []; // Array to hold log messages.

		// Check if billing address has changed.
		if ( $old_billing_address !== $new_billing_address ) {
			$log_messages[] = $this->get_address_update_message('Billing Address', $new_billing_address);
		}

		// Check if shipping address has changed.
		if ( $old_shipping_address !== $new_shipping_address ) {
			$log_messages[] = $this->get_address_update_message('Shipping Address', $new_shipping_address);
		}

		// If any address was changed, log the activity.
		if ( ! empty($log_messages) ) {
			foreach ( $log_messages as $message ) {
				$this->send_slack_notification($message);
			}

			// Create a unique log message.
			$activated_by = wp_get_current_user()->display_name;
			$severity = 'Medium';
			$event_type = 'Address Update';
			$time = current_time('mysql');

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

			// Combine log messages into a single log entry.
			$log_message = "Order #{$order_id} address updated for site $site_url :\n" . implode("\n", $log_messages);

			$attachmentHandler->log_activity_to_db($severity, $time, $ip, $activated_by, $event_type, $log_message);
		}
	}


	/**
	 * Get the formatted address based on the provided arguments and address type.
	 *
	 * This function formats the address for either billing or shipping based on the provided arguments and address type.
	 *
	 * @since 1.0.0
	 * @param array  $args The address data to be formatted.
	 * @param string $type The type of address (billing or shipping).
	 * @return string The formatted address.
	 */
	private function get_formatted_address_from_args( $args, $type ) {
		$address_key = "_{$type}_";
		return WC()->countries->get_formatted_address([
			'first_name' => $args[ $address_key . 'first_name' ] ?? '',
			'last_name'  => $args[ $address_key . 'last_name' ] ?? '',
			'company'    => $args[ $address_key . 'company' ] ?? '',
			'address_1'  => $args[ $address_key . '1' ] ?? '',
			'address_2'  => $args[ $address_key . '2' ] ?? '',
			'city'       => $args[ $address_key . 'city' ] ?? '',
			'state'      => $args[ $address_key . 'state' ] ?? '',
			'postcode'   => $args[ $address_key . 'postcode' ] ?? '',
			'country'    => $args[ $address_key . 'country' ] ?? '',
			'email'      => $args[ $address_key . 'email' ] ?? '',
			'phone'      => $args[ $address_key . 'phone' ] ?? '',
		]);
	}

	/**
	 * Get the formatted shipping address from the order object.
	 *
	 * This function retrieves the shipping address of the given order in a formatted string.
	 *
	 * @since 1.0.0
	 * @param WC_Order $order The order object.
	 * @return string The formatted shipping address.
	 */
	private function get_formatted_shipping_address( $order ) {
		return $order->get_formatted_shipping_address();
	}

	/**
	 * Get the formatted billing address from the order object.
	 *
	 * This function retrieves the billing address of the given order in a formatted string.
	 *
	 * @since 1.0.0
	 * @param WC_Order $order The order object.
	 * @return string The formatted billing address.
	 */
	private function get_formatted_billing_address( $order ) {
		return $order->get_formatted_billing_address();
	}

	/**
	 * Get the address update message.
	 *
	 * This function generates a formatted message detailing the changes made to an address.
	 * It replaces any HTML line breaks with newline characters to ensure proper formatting for Slack notifications.
	 *
	 * @since 1.0.0
	 * @param string $address_type The type of address being updated (billing or shipping).
	 * @param string $new_address The new address after the update.
	 * @return string The formatted address update message.
	 */
	private function get_address_update_message( $address_type, $new_address ) {
		// Replace <br/> with newline character.
		$new_address = str_replace('<br/>', "\n", $new_address);

		// Replace <br> with newline character (in case Slack prefers this format).
		$new_address = str_replace('<br>', "\n", $new_address);

		return sprintf("Below %s update has been recorded\n%s\n", $address_type, $new_address);
	}

	/**
	 * Send a Slack notification with the provided message using reusable function with channel routing.
	 *
	 * @since 1.0.0
	 * @param string $message The message to send to Slack.
	 */
	private function send_slack_notification( $message ) {
		// Use SlackChannelRouter for channel and user tag support
		SlackChannelRouter::send_notification_with_routing(
			'wpnts_schedules_interval_woocommerce_settings',
			$message
		);
	}

	/**
	 * Enqueue checkout tracking script on checkout and cart pages
	 *
	 * @since 1.0.0
	 */
	public function enqueue_checkout_tracking_script() {

		if ( ! $this->is_woocommerce_active() || ! function_exists( 'is_checkout' ) || ! function_exists( 'is_cart' ) ) {
			return;
		}

		// Only load on checkout or cart pages
		if ( ! is_checkout() && ! is_cart() ) {
			return;
		}

		// Use enhanced tracking script
		wp_enqueue_script(
			'wpnts-checkout-tracking',
			WP_NOTIFIER_TO_SLACK_URL . '/assets/js/wpnts-enhanced-checkout-tracking.js',
			array( 'jquery' ),
			WP_NOTIFIER_TO_SLACK_VERSION,
			true
		);

		wp_localize_script(
			'wpnts-checkout-tracking',
			'wpnts_checkout_ajax',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'wpnts_checkout_tracking' ),
			)
		);
	}


	/**
	 * Safely check if we're on a WooCommerce page
	 *
	 * @return bool
	 */
	private function is_woocommerce_page() {
		if ( ! $this->is_woocommerce_active() ) {
			return false;
		}

		// Check if WooCommerce conditional functions exist before using them
		$wc_functions = [
			'is_woocommerce',
			'is_cart',
			'is_checkout',
			'is_shop',
			'is_product',
			'is_product_category',
			'is_product_tag',
			'is_account_page'
		];

		foreach ( $wc_functions as $function ) {
			if ( ! function_exists( $function ) ) {
				return false;
			}
		}

		return is_woocommerce() || is_cart() || is_checkout() || is_shop() || is_product() || 
		       is_product_category() || is_product_tag() || is_account_page();
	}

	/**
	 * Enqueue cart session tracking script
	 *
	 * @since 1.0.0
	 */
	public function enqueue_cart_session_tracking_script() {
		// Load on all WooCommerce related pages
		if ( ! $this->is_woocommerce_page() ) {
			return;
		}

		wp_enqueue_script(
			'wpnts-cart-session-tracking',
			WP_NOTIFIER_TO_SLACK_URL . '/assets/js/wpnts-cart-session-tracker.js',
			array( 'jquery' ),
			WP_NOTIFIER_TO_SLACK_VERSION,
			true
		);

		wp_localize_script(
			'wpnts-cart-session-tracking',
			'wpnts_cart_session_ajax',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'wpnts_cart_session' ),
			)
		);
	}

	/**
	 * Mark order as complete when checkout is processed
	 *
	 * @since 1.0.0
	 * @param int $order_id Order ID
	 * @param array $posted_data Posted data
	 * @param WC_Order $order Order object
	 */
	public function mark_order_complete( $order_id, $posted_data, $order ) {
		try {
			if ( ! $order_id ) {
				
				return;
			}

			if ( ! is_object( $order ) || ! method_exists( $order, 'get_id' ) ) {
			
				return;
			}

		
			$wpnts_db_instance = new DB();
			$wpnts_db_instance->mark_incomplete_order_complete( $order );
		} catch ( Exception $e ) {
			// error_log('[WPNTS] ❌ Error in mark_order_complete: ' . $e->getMessage());
		}
	}

	/**
	 * Mark order as complete for block checkout
	 *
	 * @since 1.0.0
	 * @param WC_Order $order Order object
	 */
	public function mark_order_complete_block( $order ) {
		try {
			if ( is_object( $order ) && method_exists( $order, 'get_id' ) ) {
			
				$wpnts_db_instance = new DB();
				$wpnts_db_instance->mark_incomplete_order_complete( $order );
			} 
		} catch ( Exception $e ) {
			// error_log('[WPNTS] ❌ Error in mark_order_complete_block: ' . $e->getMessage());
		}
	}

	/**
	 * Send scheduled incomplete order notification
	 *
	 * @since 1.0.0
	 * @param int $order_id Incomplete order ID
	 */
	public function send_scheduled_incomplete_order_notification( $order_id ) {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'wpnts_incomplete_orders';
		$incomplete_order = $wpdb->get_row( $wpdb->prepare(
			"SELECT * FROM {$table_name} WHERE id = %d AND status = 'incomplete'",
			$order_id
		) );
		
		if ( $incomplete_order ) {
			
			$this->send_incomplete_order_notification( (array) $incomplete_order );
		} 
	}

	/**
	 * Send incomplete order notification to Slack
	 *
	 * @since 1.0.0
	 * @param array $incomplete_order_data Incomplete order data
	 */
	public function send_incomplete_order_notification( $incomplete_order_data ) {
		
		$schedules_int = get_option('wpnts_schedules_interval_woocommerce_settings');
		$schedules_interval = json_decode($schedules_int);
		$slack_notifications_enabled = $schedules_interval->incomplete_orders_slack_notifications ?? true;

		if ( ! $slack_notifications_enabled ) {
		
			return;
		}

		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$customer_name = $incomplete_order_data['name'] ?: 'Unknown Customer';
		$customer_email = $incomplete_order_data['email'] ?: 'No email provided';
		$product_names = json_decode( $incomplete_order_data['product_names'], true );
		$total_amount = $incomplete_order_data['total_amount'];

		$message = "🛒 **Incomplete Order Alert**\n\n";
		$message .= "**Customer:** {$customer_name} ({$customer_email})\n";
		$message .= "**Products:** " . implode( ', ', $product_names ) . "\n";
		$message .= "**Estimated Value:** $" . number_format( $total_amount, 2 ) . "\n";
		$message .= "**Time:** " . $incomplete_order_data['created_at'] . "\n";
		$message .= "**Site:** {$site_url}\n\n";
		$message .= "💡 *Consider reaching out to recover this potential sale!*";

		// Send notification and log activity with channel routing
	
		$attachmentHandler->send_notification_and_log(
			$schedules_interval->webhook ?? '',
			$message,
			'Medium',
			'Incomplete Order',
			$customer_name,
			[],
			'wpnts_schedules_interval_woocommerce_settings'
		);
	}


	/**
	 * Check if WooCommerce is active and loaded
	 *
	 * @return bool
	 */
	private function is_woocommerce_active() {
		return class_exists( 'WooCommerce' ) && function_exists( 'WC' );
	}

}
