<?php
/**
 * Order Actions — manual notification resend from WooCommerce order screen.
 *
 * Adds a "Mersal Notifications" meta box to the order edit screen with
 * one-click resend buttons for WhatsApp, SMS, and Email. Also adds
 * notification buttons to the orders list column.
 *
 * @package Mersal_Notif
 */

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

class Mersal_Notif_Order_Actions {

	/**
	 * @var Mersal_Notif_Core
	 */
	private $core;

	/**
	 * @param Mersal_Notif_Core $core Notification engine.
	 */
	public function __construct( $core ) {
		$this->core = $core;
	}

	/**
	 * Initialize hooks.
	 */
	public function init() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		// Meta box on the order edit screen (display-only: resend buttons that
		// send over AJAX — there is nothing to persist on order save).
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );

		// AJAX handler for sending.
		add_action( 'wp_ajax_mnotif_resend_order', array( $this, 'ajax_resend' ) );

		// Column on the orders list — legacy posts table and HPOS table.
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_column' ) );
		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'render_column' ), 10, 2 );
		add_filter( 'manage_woocommerce_page_wc-orders_columns', array( $this, 'add_column' ) );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $this, 'render_column' ), 10, 2 );
	}

	/**
	 * Add meta box to the order edit screen (legacy post editor + HPOS editor).
	 */
	public function add_meta_box() {
		$screens = array( 'shop_order' );
		if ( function_exists( 'wc_get_page_screen_id' ) ) {
			$hpos = wc_get_page_screen_id( 'shop-order' );
			if ( $hpos && ! in_array( $hpos, $screens, true ) ) {
				$screens[] = $hpos;
			}
		}
		foreach ( $screens as $screen ) {
			add_meta_box(
				'mersal-notifications',
				__( 'Mersal Notifications', 'mersal-notifications' ),
				array( $this, 'render_meta_box' ),
				$screen,
				'side',
				'high'
			);
		}
	}

	/**
	 * Render meta box content.
	 *
	 * @param WP_Post|WC_Order $post Order post (legacy) or order object (HPOS).
	 */
	public function render_meta_box( $post ) {
		$order = ( $post instanceof WC_Order ) ? $post : wc_get_order( $post->ID );
		if ( ! $order ) {
			return;
		}
		$order_id = $order->get_id();

		$phone = $order->get_billing_phone();
		$email = $order->get_billing_email();
		$rules = $this->get_matching_rules( $order );

		wp_nonce_field( 'mnotif_order_' . $order_id, 'mnotif_order_nonce' );

		if ( empty( $rules ) ) {
			echo '<p style="color:#999;">' . esc_html__( 'No matching notification rules for this order status.', 'mersal-notifications' ) . '</p>';
			return;
		}

		echo '<div class="mnotif-order-actions">';
		echo '<p style="margin:0 0 8px;"><strong>' . esc_html__( 'Send notification:', 'mersal-notifications' ) . '</strong></p>';

		foreach ( $rules as $rule ) {
			$channels = array();
			if ( in_array( 'whatsapp', $rule['channels'] ?? array(), true ) && ! empty( $phone ) ) {
				$channels[] = 'whatsapp';
			}
			if ( in_array( 'sms', $rule['channels'] ?? array(), true ) && ! empty( $phone ) ) {
				$channels[] = 'sms';
			}
			if ( in_array( 'email', $rule['channels'] ?? array(), true ) && ! empty( $email ) ) {
				$channels[] = 'email';
			}

			if ( empty( $channels ) ) {
				continue;
			}

			echo '<p style="margin:8px 0 4px;font-size:12px;color:#666;">' . esc_html( $rule['name'] ) . '</p>';
			echo '<div style="display:flex;gap:4px;flex-wrap:wrap;">';

			foreach ( $channels as $ch ) {
				$label = 'whatsapp' === $ch ? 'WhatsApp' : ( 'sms' === $ch ? 'SMS' : 'Email' );
				$icon  = 'whatsapp' === $ch ? '&#x1F4AC;' : ( 'sms' === $ch ? '&#x1F4E9;' : '&#x2709;' );
				printf(
					'<button type="button" class="button mnotif-resend-btn" data-order="%d" data-rule="%s" data-channel="%s" data-nonce="%s" style="font-size:12px;padding:4px 8px;">%s %s</button>',
					esc_attr( $order_id ),
					esc_attr( $rule['id'] ),
					esc_attr( $ch ),
					esc_attr( wp_create_nonce( 'mnotif_order_' . $order_id ) ),
					$icon,
					esc_html( $label )
				);
			}

			echo '</div>';
		}

		echo '<div id="mnotif-resend-msg" style="margin-top:8px;display:none;padding:6px;border-radius:4px;font-size:12px;"></div>';
		echo '</div>';

		$this->print_resend_js();
	}

	/**
	 * Shared click handler for the resend buttons (meta box + orders list).
	 * Printed at most once per page.
	 */
	private function print_resend_js() {
		static $printed = false;
		if ( $printed ) {
			return;
		}
		$printed = true;
		?>
		<script>
		jQuery(function($){
			$(document).on('click','.mnotif-resend-btn',function(){
				var $btn=$(this),orderId=$btn.data('order'),ruleId=$btn.data('rule'),channel=$btn.data('channel');
				var $msg=$('#mnotif-resend-msg');
				var old=$btn.text();
				$btn.prop('disabled',true);
				if($msg.length){$msg.hide();}
				$.post(ajaxurl,{
					action:'mnotif_resend_order',
					order_id:orderId,
					rule_id:ruleId,
					channel:channel,
					nonce:$btn.data('nonce')||$('#mnotif_order_nonce').val()
				},function(r){
					$btn.prop('disabled',false);
					if($msg.length){
						$msg.show().css('background',r.success?'#d4edda':'#f8d7da').css('color',r.success?'#155724':'#721c24').text((r.data&&r.data.message)||'');
					}else{
						$btn.text(r.success?'✓':'✗');
						setTimeout(function(){$btn.text(old);},1800);
					}
				}).fail(function(){
					$btn.prop('disabled',false);
					if($msg.length){
						$msg.show().css('background','#f8d7da').css('color','#721c24').text('<?php echo esc_js( __( 'Request failed.', 'mersal-notifications' ) ); ?>');
					}else{
						$btn.text('✗');
						setTimeout(function(){$btn.text(old);},1800);
					}
				});
			});
		});
		</script>
		<?php
	}

	/**
	 * AJAX: Resend notification for an order.
	 */
	public function ajax_resend() {
		check_ajax_referer( 'mnotif_order_' . absint( $_POST['order_id'] ?? 0 ), 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'mersal-notifications' ) ) );
		}

		$order_id = absint( $_POST['order_id'] ?? 0 );
		$rule_id  = sanitize_text_field( wp_unslash( $_POST['rule_id'] ?? '' ) );
		$channel  = sanitize_key( $_POST['channel'] ?? '' );

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( array( 'message' => __( 'Order not found.', 'mersal-notifications' ) ) );
		}

		$rule = $this->core->get_rule( $rule_id );
		if ( ! $rule ) {
			wp_send_json_error( array( 'message' => __( 'Rule not found.', 'mersal-notifications' ) ) );
		}

		$to = 'email' === $channel ? $order->get_billing_email() : $order->get_billing_phone();
		if ( empty( $to ) ) {
			wp_send_json_error( array( 'message' => __( 'No recipient available.', 'mersal-notifications' ) ) );
		}

		$replacements = $this->core->order_replacements( $order, $order->get_status(), $order->get_status() );
		$message      = $this->core->parse( $rule['message'], $replacements );
		$subject      = $this->core->parse( $rule['email_subject'] ?? '', $replacements );

		$job = array(
			'channel' => $channel,
			'to'      => $to,
			'message' => $message,
			'subject' => $subject,
			'media'   => '',
			'rule'    => $rule['name'],
			'rule_id' => $rule['id'],
		);

		// Use reflection to access the private dispatch method.
		try {
			$ref    = new ReflectionClass( $this->core );
			$method = $ref->getMethod( 'dispatch' );
			$method->setAccessible( true );
			$method->invoke( $this->core, $job );
		} catch ( ReflectionException $e ) {
			wp_send_json_error( array( 'message' => __( 'Failed to send notification.', 'mersal-notifications' ) ) );
		}

		wp_send_json_success( array( 'message' => __( 'Notification sent.', 'mersal-notifications' ) ) );
	}

	/**
	 * Get matching rules for an order's current status.
	 *
	 * @param WC_Order $order Order.
	 * @return array
	 */
	private function get_matching_rules( $order ) {
		$status = $order->get_status();
		$key    = 'wc_status_' . $status;
		$rules  = array();
		foreach ( $this->core->get_rules() as $rule ) {
			if ( ! empty( $rule['enabled'] ) && $rule['trigger_key'] === $key ) {
				$rules[] = $rule;
			}
		}
		return $rules;
	}

	/**
	 * Add notification column to orders list.
	 *
	 * @param array $columns Columns.
	 * @return array
	 */
	public function add_column( $columns ) {
		$columns['mnotif_resend'] = __( 'Notification', 'mersal-notifications' );
		return $columns;
	}

	/**
	 * Render notification column content.
	 *
	 * @param string           $column        Column name.
	 * @param int|WC_Order     $post_or_order Post ID (legacy) or order object (HPOS).
	 */
	public function render_column( $column, $post_or_order ) {
		if ( 'mnotif_resend' !== $column ) {
			return;
		}
		$order = ( $post_or_order instanceof WC_Order ) ? $post_or_order : wc_get_order( $post_or_order );
		if ( ! $order ) {
			return;
		}
		$order_id = $order->get_id();

		$rules  = $this->get_matching_rules( $order );
		$phone  = $order->get_billing_phone();
		$email  = $order->get_billing_email();

		if ( empty( $rules ) ) {
			echo '<span style="color:#999;">—</span>';
			return;
		}

		$rule  = $rules[0]; // Use first matching rule.
		$nonce = wp_create_nonce( 'mnotif_order_' . $order_id );
		echo '<div style="display:flex;gap:2px;">';
		if ( ! empty( $phone ) && in_array( 'whatsapp', $rule['channels'] ?? array(), true ) ) {
			printf(
				'<button type="button" class="button mnotif-resend-btn" data-order="%d" data-rule="%s" data-channel="whatsapp" data-nonce="%s" title="WhatsApp" style="padding:2px 6px;font-size:11px;">WA</button>',
				esc_attr( $order_id ),
				esc_attr( $rule['id'] ),
				esc_attr( $nonce )
			);
		}
		if ( ! empty( $phone ) && in_array( 'sms', $rule['channels'] ?? array(), true ) ) {
			printf(
				'<button type="button" class="button mnotif-resend-btn" data-order="%d" data-rule="%s" data-channel="sms" data-nonce="%s" title="SMS" style="padding:2px 6px;font-size:11px;">SMS</button>',
				esc_attr( $order_id ),
				esc_attr( $rule['id'] ),
				esc_attr( $nonce )
			);
		}
		if ( ! empty( $email ) && in_array( 'email', $rule['channels'] ?? array(), true ) ) {
			printf(
				'<button type="button" class="button mnotif-resend-btn" data-order="%d" data-rule="%s" data-channel="email" data-nonce="%s" title="Email" style="padding:2px 6px;font-size:11px;">Email</button>',
				esc_attr( $order_id ),
				esc_attr( $rule['id'] ),
				esc_attr( $nonce )
			);
		}
		echo '</div>';

		$this->print_resend_js();
	}
}
