<?php
/**
 * Order Actions Helper.
 *
 * @package automation-web-platform
 */

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

/**
 * Class WAWP_Order_Actions
 */
class WAWP_Order_Actions {
	use WAWP_Security_Trait;

	/**
	 * Constructor.
	 */
	public function __construct() {
		// Use priority 0 to be before almost everyone else.
		add_action( 'add_meta_boxes', array( $this, 'add_order_meta_box' ), 0 );

		// AJAX handler for the metabox "Send Notification" button.
		add_action( 'wp_ajax_wawp_send_manual_notification', array( $this, 'ajax_send_manual_notification' ) );
	}

	/**
	 * Add Wawp meta box to the order screen.
	 */
	public function add_order_meta_box() {
		// Register for traditional shop_order post type.
		$screen_post = 'shop_order';

		// Register for HPOS custom table screen.
		$screen_hpos = 'woocommerce_page_wc-orders';
		foreach ( array( $screen_post, $screen_hpos ) as $screen ) {
			add_meta_box( 'wawp_order_actions', esc_html__( 'Wawp Actions', 'automation-web-platform' ), array( $this, 'render_meta_box' ), $screen, 'side', 'high' );
		}

		// Aggressively force order for all relevant screens.
		add_filter( 'get_user_option_meta-box-order_shop_order', array( $this, 'force_meta_box_order' ), 999 );
		add_filter( 'get_user_option_meta-box-order_woocommerce_page_wc-orders', array( $this, 'force_meta_box_order' ), 999 );
	}

	/**
	 * Force Wawp meta box to be first in the side column.
	 *
	 * @param array $value Meta box order.
	 * @return array
	 */
	public function force_meta_box_order( $value ) {
		if ( ! is_array( $value ) ) {
			$value = array(
				'side'     => '',
				'normal'   => '',
				'advanced' => '',
			);
		}

		if ( isset( $value['side'] ) ) {
			$boxes = explode( ',', $value['side'] );

			// Remove if exists and re-insert at top.
			$boxes = array_diff( $boxes, array( 'wawp_order_actions' ) );
			array_unshift( $boxes, 'wawp_order_actions' );
			$value['side'] = implode( ',', array_filter( $boxes ) );
		}

		return $value;
	}

	/**
	 * Get Wawp SVG icon.
	 *
	 * @return string
	 */
	public function get_wawp_svg_icon() {
		return WAWP_UI_Helper::get_svg(
			'main-icon',
			array(
				'width'  => 36,
				'height' => 36,
			)
		);
	}

	/**
	 * Render the Wawp order actions meta box.
	 *
	 * @param WP_Post|WC_Order|int $post_or_order Post, order object, or order ID.
	 */
	public function render_meta_box( $post_or_order ) {
		if ( ! function_exists( 'wc_get_order' ) ) {
			return;
		}
		// In HPOS, $post_or_order might be a WC_Order object.
		$is_wc_order = ( class_exists( 'WC_Order' ) && $post_or_order instanceof WC_Order );
		$order_id    = ( $post_or_order instanceof WP_Post ) ? $post_or_order->ID : ( $is_wc_order ? $post_or_order->get_id() : $post_or_order );
		$order       = wc_get_order( $order_id );
		if ( ! $order || ! function_exists( 'wc_get_order_statuses' ) ) {
			return;
		}

		$flow_builder   = WAWP_Flow_Builder::get_instance();
		$current_status = $order->get_status();
		$all_notifs     = $flow_builder->get_all_notifications();
		$notifications  = array();
		foreach ( $all_notifs as $notif ) {
			if ( isset( $notif['trigger_key'] ) && 'wc_status_' . $current_status === $notif['trigger_key'] ) {
				$notifications[] = $notif;
			}
		}
		$svg      = $this->get_wawp_svg_icon();
		$logo_url = 'data:image/svg+xml;utf8,' . rawurlencode( $svg );
		?>
		<div class="wawp-order-actions-container">
			<div class="wawp-meta-header">
				<img src="<?php echo esc_attr( $logo_url ); ?>" alt="Wawp" style="width: 24px; vertical-align: middle;">
				<span style="font-weight: bold; margin-left: 5px;"><?php esc_html_e( 'Manual Notifications', 'automation-web-platform' ); ?></span>
			</div>
			<p class="description">
				<?php esc_html_e( 'Send order status notifications to customer without changing the order status.', 'automation-web-platform' ); ?>
			</p>
			<div class="wawp-action-field" style="margin-bottom: 10px;">
				<label for="wawp_status_select" style="display: block; margin-bottom: 5px;"><?php esc_html_e( 'Select Notification:', 'automation-web-platform' ); ?></label>
				<select id="wawp_status_select" style="width: 100%;">
					<?php
					foreach ( $notifications as $notif ) :
						$sender_type      = $notif['sender_type'] ?? '';
						$whatsapp_enabled = ! empty( $notif['whatsapp_enabled'] );
						$is_meta          = str_contains( $sender_type, 'meta' );
						$email_enabled    = ! empty( $notif['email_enabled'] );

						$wa_web  = ( $whatsapp_enabled && ! $is_meta ) ? '1' : '0';
						$wa_meta = ( $whatsapp_enabled && $is_meta ) ? '1' : '0';
						$email   = $email_enabled ? '1' : '0';
						?>
						<option value="<?php echo esc_attr( $notif['id'] ); ?>" data-wa-web="<?php echo esc_attr( $wa_web ); ?>" data-wa-meta="<?php echo esc_attr( $wa_meta ); ?>" data-email="<?php echo esc_attr( $email ); ?>">
							<?php echo esc_html( $notif['name'] ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>
			<button type="button" class="button button-primary wawp-send-btn whatsapp-web wawp-hide" data-gateway="whatsapp" data-order-id="<?php echo esc_attr( $order_id ); ?>" style="margin-bottom: 6px;">
				<img src="<?php echo esc_url( WAWP_PLUGIN_URL . 'assets/icons/whatsapp.svg' ); ?>" alt="WhatsApp" style="width: 18px; height: 18px; display: inline-block; vertical-align: middle; filter: brightness(0) invert(1);">
				<?php esc_html_e( 'Send WhatsApp Web', 'automation-web-platform' ); ?>
			</button>
			<button type="button" class="button button-primary wawp-send-btn whatsapp-meta wawp-hide" data-gateway="meta" data-order-id="<?php echo esc_attr( $order_id ); ?>" style="margin-bottom: 6px;">
				<img src="<?php echo esc_url( WAWP_PLUGIN_URL . 'assets/icons/meta.svg' ); ?>" alt="Meta JID" style="width: 18px; height: 18px; display: inline-block; vertical-align: middle; filter: brightness(0) invert(1);">
				<?php esc_html_e( 'Send WhatsApp Meta', 'automation-web-platform' ); ?>
			</button>
			<button type="button" class="button button-primary wawp-send-btn email wawp-hide" data-gateway="email" data-order-id="<?php echo esc_attr( $order_id ); ?>">
				<img src="<?php echo esc_url( WAWP_PLUGIN_URL . 'assets/icons/email.svg' ); ?>" alt="Email" style="width: 18px; height: 18px; display: inline-block; vertical-align: middle; filter: brightness(0) invert(1);">
				<?php esc_html_e( 'Send Email', 'automation-web-platform' ); ?>
			</button>
			<div id="wawp_action_message" style="margin-top: 5px;"></div>
		</div>
		<script type="text/javascript">
		jQuery( document ).ready(
			function ($) {
				function updateWawpButtonVisibility() {
					var $select = $( '#wawp_status_select' );
					if ( ! $select.length ) {
						return;
					}
					var $option = $select.find( 'option:selected' );
					if ( ! $option.length ) {
						$( '.wawp-send-btn' ).addClass( 'wawp-hide' );
						return;
					}
					var waWeb  = $option.attr( 'data-wa-web' ) === '1';
					var waMeta = $option.attr( 'data-wa-meta' ) === '1';
					var email  = $option.attr( 'data-email' ) === '1';

					$( '.wawp-send-btn.whatsapp-web' ).toggleClass( 'wawp-hide', ! waWeb );
					$( '.wawp-send-btn.whatsapp-meta' ).toggleClass( 'wawp-hide', ! waMeta );
					$( '.wawp-send-btn.email' ).toggleClass( 'wawp-hide', ! email );
				}
				$( '#wawp_status_select' ).on( 'change', updateWawpButtonVisibility );
				updateWawpButtonVisibility();
			}
		);
		</script>
		<?php
	}
	/**
	 * AJAX handler for the metabox "Send Notification" button.
	 *
	 * Validates the nonce, finds the order, picks the requested status,
	 * then calls the flow builder so the activity log shows the correct
	 * order number and trigger label instead of an unrelated OTP event.
	 */
	public function ajax_send_manual_notification() {
		check_ajax_referer( 'wawp_order_actions_nonce', 'nonce' );

		$capability = 'manage_woocommerce';
		if ( ! current_user_can( $capability ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Insufficient permissions.', 'automation-web-platform' ) ) );
			return;
		}

		$order_id       = isset( $_POST['order_id'] ) ? absint( wp_unslash( $_POST['order_id'] ) ) : 0;
		$status_request = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : '';

		if ( ! $order_id ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid order ID.', 'automation-web-platform' ) ) );
			return;
		}

		if ( ! function_exists( 'wc_get_order' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'WooCommerce is not available.', 'automation-web-platform' ) ) );
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Order not found.', 'automation-web-platform' ) ) );
			return;
		}

		if ( ! class_exists( 'WAWP_Flow_Builder' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Notification system unavailable.', 'automation-web-platform' ) ) );
			return;
		}

		$flow_builder = WAWP_Flow_Builder::get_instance();
		$status       = $status_request ? $status_request : $order->get_status();

		$log_label = sprintf(
			/* translators: %s: order number */
			esc_html__( 'Manual Notification Request (Order #%s)', 'automation-web-platform' ),
			$order->get_order_number()
		);

		if ( ! empty( $_POST['status'] ) ) {
			$rule_id  = sanitize_text_field( wp_unslash( $_POST['status'] ) );
			$settings = $flow_builder->get_settings();
			$user_id  = $order->get_customer_id();
			$locale   = $user_id ? get_user_locale( $user_id ) : ( $settings['main_language_code'] ? $settings['main_language_code'] : ( WAWP::instance()->get_wawp_setting( 'WPLANG' ) ? WAWP::instance()->get_wawp_setting( 'WPLANG' ) : 'en_US' ) );

			$rule = $flow_builder->get_rule_by_id( $settings, $locale, $rule_id );
			if ( $rule ) {
				$billing_email = $order->get_billing_email();
				$billing_phone = $order->get_billing_phone();
				if ( empty( $billing_phone ) && $user_id ) {
					$billing_phone = WAWP()->user_manager->get_user_phone( $user_id );
				}

				$all_statuses  = function_exists( 'wc_get_order_statuses' ) ? wc_get_order_statuses() : array();
				$new_status    = str_replace( 'wc_status_', '', $rule['trigger_key'] );
				$new_label     = isset( $all_statuses[ 'wc-' . $new_status ] ) ? $all_statuses[ 'wc-' . $new_status ] : $new_status;
				$customer_name = $order->get_formatted_billing_full_name() ? $order->get_formatted_billing_full_name() : ( $user_id ? get_userdata( $user_id )->display_name : esc_html__( 'Customer', 'automation-web-platform' ) );

				$replacements_user = array(
					'{{order_id}}'               => $order_id,
					'{{wc-order}}'               => $order->get_order_number(),
					'{{customer_name}}'          => $customer_name,
					'{{billing_first_name}}'     => $order->get_billing_first_name(),
					'{{billing_last_name}}'      => $order->get_billing_last_name(),
					'{{order_total}}'            => html_entity_decode( wp_strip_all_tags( $order->get_formatted_order_total() ), ENT_QUOTES, 'UTF-8' ),
					'{{sitename}}'               => get_bloginfo( 'name' ),
					'{{siteurl}}'                => get_site_url(),
					'{{user_email}}'             => $billing_email,
					'{{billing_email}}'          => $billing_email,
					'{{billing_phone}}'          => $billing_phone,
					'{{status}}'                 => $new_label,
					'{{order_status_label}}'     => $new_label,
					'{{old_order_status_label}}' => $new_label,
				);

				$recipient_user = array(
					'user_id'      => $user_id,
					'email'        => $billing_email,
					'phone'        => $billing_phone,
					'display_name' => $customer_name,
				);

				$context = $flow_builder->prepare_object_context( $order );

				$flow_builder->apply_image_overrides( $rule, $context );
				if ( ! $flow_builder->evaluate_rule_filters( $rule, $context ) ) {
					if ( str_contains( $rule['sender_type'] ?? '', 'admin' ) ) {
						$rule['sender_type'] = str_replace( 'user_', '', $rule['sender_type'] );
					}
				}

				// Force the sender type and message structure based on the clicked gateway button.
				$forced_gateway = isset( $_POST['gateway'] ) ? sanitize_text_field( wp_unslash( $_POST['gateway'] ) ) : '';
				if ( 'whatsapp' === $forced_gateway ) {
					$rule['sender_type'] = 'user_whatsapp';
				} elseif ( 'meta' === $forced_gateway ) {
					$rule['sender_type'] = 'user_meta';
				} elseif ( 'email' === $forced_gateway ) {
					$rule['sender_type'] = 'user_email';
					if ( ! empty( $rule['email_body'] ) ) {
						$rule['whatsapp_message'] = $rule['email_body'];
					}
				}

				// Always deliver manual actions synchronously/instantly for immediate feedback & logging.
				$rule['send_timing'] = 'instant';

				$flow_builder->schedule_or_send( $rule, $replacements_user, $recipient_user, $log_label, $order_id, $rule['trigger_key'] );
				wp_send_json_success( array( 'message' => esc_html__( 'Notification sent successfully.', 'automation-web-platform' ) ) );
				return;
			}
		}

		$flow_builder->handle_order_status_change( $order_id, $status, $status, $order, $log_label );

		wp_send_json_success( array( 'message' => esc_html__( 'Notification sent successfully.', 'automation-web-platform' ) ) );
	}
}

new WAWP_Order_Actions();
