<?php
namespace ApproveOrders;

use ApproveOrders\Settings as AOFWC_Settings;
use ApproveOrders\Modules\PendingPaymentNotification as AOFWC_PendingPaymentEmail;
use ApproveOrders\Modules\ApprovedOrderNotification as AOFWC_ApprovedOrderEmail;
use ApproveOrders\Modules\RejectedOrderNotification as AOFWC_RejectedOrderEmail;
use ApproveOrders\Modules\AdminAwaitingApprovalNotification as AOFWC_AwaitingApprovalEmail;
use ApproveOrders\Modules\Rules as AOFWC_Rules;
use ApproveOrders\Helper as AOFWC_Helper;

/**
 * The back-end plugin class for Approve Orders.
 */
class Backend {

	/**
	 * Initialize the back-end functionality of the plugin.
	 */
	public function init() {
		// Code for the constructor
		add_action( 'admin_menu', array( $this, 'register_settings_menu' ) );
		// Admin Init
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_init', array( $this, 'save_approve_orders_settings' ) );
		// Register a new order status
		add_action( 'init', array( $this, 'register_custom_order_status' ) );
		// Add the new order status to the list of order statuses in WooCommerce
		add_filter( 'wc_order_statuses', array( $this, 'add_custom_order_statuses' ) );
		// Add the new order status to the admin order list
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_custom_order_status_column' ) );
		// Display the custom order status in the admin order list
		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'display_custom_order_status_column' ) );
		// Add to WooCommerce Email Classes
		add_filter( 'woocommerce_email_classes', array( $this, 'add_order_notification_email' ) );
		add_filter( 'woocommerce_email_actions', array( $this, 'add_order_notification_action' ) );
		// Trigger the custom email when order status changes to pending
		add_action( 'woocommerce_order_status_changed', array( $this, 'send_order_notification' ), 10, 3 );
		// Add buttons to the WooCommerce order edit page
		add_action( 'woocommerce_order_item_add_action_buttons', array( $this, 'add_buttons_to_order_edit_page' ) );
		// Admin Footer
		add_filter( 'admin_footer_text', array( $this, 'replace_footer' ) );
		add_filter( 'update_footer', array( $this, 'replace_version' ), 99 );

		if ( ao_fs()->is_paying_or_trial() ) {
			// Register bulk actions
			add_filter( 'bulk_actions-woocommerce_page_wc-orders', array( $this, 'bulk_actions__premium_only' ) );
			add_action( 'handle_bulk_actions-woocommerce_page_wc-orders', array( $this, 'handle_bulk_actions__premium_only' ), 10, 3 );
			// Show approver in Order Details
			add_action( 'woocommerce_admin_order_data_after_shipping_address', array( $this, 'show_approver__premium_only' ) );
		}
	}

	/**
	 * Add Admin Menu
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function register_settings_menu() {
		add_menu_page(
			__( 'Approve Orders', 'approve-orders' ),
			__( 'Approve Orders', 'approve-orders' ),
			'manage_options',
			'approve-orders',
			array( $this, 'render_settings_page' ),
			'dashicons-saved',
			25
		);
	}

	/**
	 * Register Approve Order Settings
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function register_settings() {
		register_setting(
			'aofwc_settings',
			'aofwc_option',
			array( $this, 'sanitize_callback' )
		);
	}

	/**
	 * Render Settings Page
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function render_settings_page() {

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$default_tab = AOFWC_PLUGIN_SLUG;
		$page = isset( $_GET['page'] ) ? $_GET['page'] : ''; // phpcs:ignore 

		$tab = isset( $_GET['tab'] ) ? $_GET['tab'] : $default_tab; // phpcs:ignore
		$tab = str_replace( 'aofwc-', '', $tab );

		$settings = AOFWC_Settings::get_instance();
		$option   = $settings->get();

		$approved_status   = isset( $option['approved_status'] ) ? $option['approved_status'] : '';
		$rejected_status   = isset( $option['rejected_status'] ) ? $option['rejected_status'] : '';
		$approval_workflow = isset( $option['approval_workflow'] ) ? $option['approval_workflow'] : 'disabled';
		$selected_gateways = isset( $option['selected_gateways'] ) ? $option['selected_gateways'] : array();
		$selected_roles    = isset( $option['selected_roles'] ) ? $option['selected_roles'] : array();

		$order_statuses     = wc_get_order_statuses(); // Get all available order statuses
		$available_gateways = \WC_Payment_Gateways::instance()->get_available_payment_gateways();
		$available_roles    = ( function_exists( 'wp_roles' ) ) ? wp_roles()->roles : array();
		$linemanager_ui     = isset( $option['linemanager_ui'] ) ? $option['linemanager_ui'] : 'disabled';
		$show_export_ui     = ( ao_fs()->is_paying() && 'enabled' === $linemanager_ui );

		if ( 'approve-orders' === $page ) {

			// Base admin URL for tabs
			$base_url  = admin_url( 'admin.php?page=approve-orders&tab=' );
			$rules_tab = ao_fs()->is_paying() ? __( 'Rules', 'approve-orders' ) : __( 'Rules ( PRO )', 'approve-orders' );

			if ( ao_fs()->is_paying_or_trial() ) {
				// Hook for addons to add more tabs dynamically
				ob_start();
				do_action( 'AOFWC_NAV_TABS', $base_url, $tab );
				$nav_tabs = ob_get_clean();
			}

			echo '<div align="center" class="pt-3">
				  <a href="' . esc_url( $base_url . 'settings' ) . '" class="settingstab-link button ' . ( 'settings' === $tab ? 'button-primary' : '' ) . '">' . esc_html__( 'Settings', 'approve-orders' ) . '</a> ';
			echo '<a href="' . esc_url( $base_url . 'rules' ) . '" class="settingstab-link button ' . ( 'rules' === $tab ? 'button-primary' : '' ) . '">' . esc_html( $rules_tab ) . '</a> ';

			if ( ao_fs()->is_paying_or_trial() ) {
				// Hook for addons to add more tabs dynamically
				echo wp_kses_post( $nav_tabs );
			}

			echo '<a target="_blank" href="' . esc_url( AOFWC_KB_URL ) . '" class="settingstab-link button">' . esc_html( 'Documentation', 'approve-orders' ) . '</a>				
			 </div>';
		}

		echo '<div class="wrap"><div class="container">';

		// Show settings tab
		if ( 'settings' === $tab ) {

			echo wp_kses_post(
				sprintf(
					'<div class="pt-1 pb-4">Enable Approve Orders at <a target="_blank" href="%1$s" class="payment-link">Payments</a> to add a verification step for smoother transactions. Customize <a target="_blank" href="%2$s" class="email-link">Emails</a> to align with your brand and enhance communication with personalized templates and automated responses.</div>',
					esc_url( admin_url( 'admin.php?page=wc-settings&tab=checkout' ) ),
					esc_url( admin_url( 'admin.php?page=wc-settings&tab=email' ) )
				)
			);

			if ( $show_export_ui ) {
				echo wp_kses_post(
					'<div id="aofwc-export-loader" class="d-flex justify-content-center align-items-center mt-3 d-none">
						<div class="spinner-border text-primary me-2" role="status">
							<span class="visually-hidden">Loading...</span>
						</div>
						<span id="aofwc-export-progress" class="text-center">Preparing export...</span>
					</div>'
				);
			}

			?>			
				<div class="aofwc-title">
					<div class="row">
						<div class="col"><?php esc_html_e( 'Approve Order Settings', 'approve-orders' ); ?></div>
						<?php if ( $show_export_ui ) { ?>	
						<div class="col text-end">
							<a id="aofwc-export-linemanager" href="#" class="button"><?php esc_html_e( 'Export Line Manager Meta', 'approve-orders' ); ?></a>
						</div>
						<?php } ?>
					</div>
				</div>

				<form method="post" action="options.php">
					<?php
					settings_fields( 'aofwc_settings' );
					wp_nonce_field( 'aofwc_settings_save', 'aofwc_nonce' );
					?>
						<table class="form-table">
							<tr>
								<th scope="row1"><?php esc_html_e( 'Order Approval Process', 'approve-orders' ); ?></th>
								<td>
									<input type="hidden" name="aofwc_option[approval_workflow]" value="disabled" />							
									<input type = 'checkbox' name = 'aofwc_option[approval_workflow]' value = 'enabled' <?php checked( $approval_workflow === 'enabled', true ); ?> />
									<p class="description"><?php esc_html_e( '( Set new orders to \'Awaiting Approval\' across the entire site )', 'approve-orders' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row1"><?php esc_html_e( 'Status after Approval', 'approve-orders' ); ?></th>
								<td>
									<select class="regular-text wc-enhanced-select" name="aofwc_option[approved_status]">
										<?php foreach ( $order_statuses as $status => $label ) { ?>
											<option value="<?php echo esc_attr( $status ); ?>" <?php selected( $approved_status, $status ); ?>><?php echo esc_html( $label ); ?></option>
										<?php } ?>
									</select>
									<p class="description"><?php esc_html_e( '( Set the order status for approved orders )', 'approve-orders' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row1"><?php esc_html_e( 'Status after Rejection', 'approve-orders' ); ?></th>
								<td>
									<select class="regular-text wc-enhanced-select" name="aofwc_option[rejected_status]">
										<?php foreach ( $order_statuses as $status => $label ) { ?>
											<option value="<?php echo esc_attr( $status ); ?>" <?php selected( $rejected_status, $status ); ?>><?php echo esc_html( $label ); ?></option>
										<?php } ?>
									</select>
									<p class="description"><?php esc_html_e( '( Set the order status for rejected orders )', 'approve-orders' ); ?></p>
								</td>
							</tr>					
							<tr>
								<th scope="row1"><?php esc_html_e( 'Payment Gateway for Order Approval', 'approve-orders' ); ?></th>
								<td>													
									<select multiple class="regular-text wc-enhanced-select" name="aofwc_option[selected_gateways][]">
										<?php foreach ( $available_gateways as $gateway ) { ?>
											<option value="<?php echo esc_attr( $gateway->id ); ?>" <?php echo in_array( $gateway->id, $selected_gateways, true ) ? 'selected' : ''; ?>><?php echo esc_html( $gateway->get_title() ); ?></option>
										<?php } ?>
									</select>
									<p class="description"><?php esc_html_e( '( Send orders for approval to selected gateways. Leave blank to allow all )', 'approve-orders' ); ?></p>							
								</td>
							</tr>
							<?php if ( ! empty( $available_roles ) ) { ?>
							<tr>
								<th scope="row1"><?php esc_html_e( 'User Role for Order Approval', 'approve-orders' ); ?></th>
								<td>													
									<select multiple class="regular-text wc-enhanced-select" name="aofwc_option[selected_roles][]">
										<?php foreach ( $available_roles as $role_key => $role ) { ?>
											<option value="<?php echo esc_attr( $role_key ); ?>" <?php echo in_array( $role_key, $selected_roles, true ) ? 'selected' : ''; ?>><?php echo esc_html( $role['name'] ); ?></option>
										<?php } ?>
									</select>
									<p class="description"><?php esc_html_e( '( Send orders for approval to selected roles. Leave blank for all )', 'approve-orders' ); ?></p>							
								</td>
							</tr>
							<?php } ?>									
						</table>
					<?php
					submit_button();
					?>
				</form>			
			<?php
		}

		// Show rules tab
		if ( 'rules' === $tab ) {

			$rules_instance = AOFWC_Rules::get_instance();

			?>
			<div class="aofwc-title"><?php esc_html_e( 'Approve Order Rules', 'approve-orders' ); ?></div>				
			<p><?php esc_html_e( 'The options below facilitate the configuration of Approve Orders for WooCommerce PRO, enhancing customer engagement.', 'approve-orders' ); ?></p>

			<div id="group-container"></div>

			<div id="button-container" style="display:none;">
				<!-- Add New Rule Group Button -->
				<button type="button" class="button button-secondary" id="add-group-btn">
					<?php esc_html_e( 'Add New Rule', 'approve-orders' ); ?>
				</button>
				<?php if ( ao_fs()->is_paying() ) { ?>						
				<!-- Save Changes Button -->
				<button type="button" class="button button-primary" id="aofwc-save-tyrules">
					<?php esc_html_e( 'Save changes', 'woocommerce' ); ?>
				</button>
				<?php } else { ?>
				<!-- Upgrade to Pro Button -->
				<span>
					<a target="_blank" href="<?php echo esc_url( ao_fs()->get_upgrade_url() ); ?>" class="button button-primary" target="_blank">
						<?php esc_html_e( 'Upgrade to Pro', 'approve-orders' ); ?>
					</a>
				</span>		
				<?php } ?>
			</div>	

			<!-- Group Template -->
			<script type="text/template" id="group-template">
				<div class="rule-group border rounded shadow p-3 mb-4">
					<!-- Header: Move and Remove Buttons -->
					<div class="d-flex justify-content-between align-items-center mb-3">
						<div class="d-flex align-items-center">
							<a href="javascript:void(0)" class="text-decoration-none">
								<i class="text-secondary dashicons dashicons-menu"></i>
							</a>
						</div>
						<div class="d-flex align-items-center">
							<a class="btn btn-sm remove-group-btn" data-bs-trigger="hover focus" data-bs-container="body" data-bs-toggle="popover" data-bs-content="<?php echo esc_attr( 'Remove Group', 'approve-orders' ); ?>">
								<i class="dashicons dashicons-remove text-danger"></i>
							</a>
						</div>
					</div>

					<!-- Toggle Checkbox for Order Options -->
					<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-xl-4 mb-3">
						<!-- Pre Order -->
						<div class="col" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-container="body" data-bs-toggle="popover" data-bs-content="<?php esc_attr_e( 'Allow customers to place orders without immediate payment, orders will require manual approval to proceed.', 'approve-orders' ); ?>">
							<input class="my-1 preOrder" type="checkbox" name="approvalAction" value="preOrder" />
							<label><?php esc_html_e( 'Pre Order', 'approve-orders' ); ?></label>
						</div>
						<!-- Send for Approval -->
						<div class="col" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-placement="top" data-bs-container="body" data-bs-toggle="popover" data-bs-content="<?php esc_attr_e( 'Send orders for manual review before processing.', 'approve-orders' ); ?>">
							<input class="my-1 sendForApproval" type="checkbox" name="approvalAction" value="sendForApproval" />
							<label><?php esc_html_e( 'Send for Approval', 'approve-orders' ); ?></label>
						</div>

						<!-- Auto Approve Order -->
						<div class="col" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-container="body" data-bs-toggle="popover" data-bs-content="<?php esc_attr_e( 'Automatically approve orders without manual intervention.', 'approve-orders' ); ?>">
							<input class="my-1 autoApproveOrder" type="checkbox" name="approvalAction" value="autoApproveOrder" />
							<label><?php esc_html_e( 'Auto Approve Order', 'approve-orders' ); ?></label>
						</div>

						<!-- Auto Reject Order -->
						<div class="col" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-container="body" data-bs-toggle="popover" data-bs-content="<?php esc_attr_e( 'Automatically reject orders that don’t meet requirements.', 'approve-orders' ); ?>">
							<input class="my-1 autoRejectOrder" type="checkbox" name="approvalAction" value="autoRejectOrder" />
							<label><?php esc_html_e( 'Auto Reject Order', 'approve-orders' ); ?></label>
						</div>						
					</div>

					<!-- Rule List (Dynamically Populated) -->
					<div class="rule-list"></div>

					<!-- Add Condition Button -->
					<button type="button" class="btn btn-secondary btn-sm add-rule-btn">
						<?php esc_html_e( 'Add Condition', 'approve-orders' ); ?>
					</button>

					<!-- Tiered Addon Template -->
					<?php
					if ( ao_fs()->is_paying_or_trial() ) {
						do_action( 'AOFWC_ADDON_TEMPLATE', $tab );
					}
					?>

				</div>
			</script>

			<!-- Rule Template -->
			<script type="text/template" id="rule-template">
				<div class="row mb-3 rule-row">
					<div class="col-md-3">
						<?php echo $rules_instance->create_dropdown_options(); // phpcs:ignore ?>
					</div>
					<div class="col-md-3">
						<?php echo $rules_instance->create_dropdown_operators(); // phpcs:ignore ?>
					</div>
					<div class="col-md-4">
						<!-- Value Input -->
						<div class="value-input">
							<input name="value" type="text" class="form-control input-value" placeholder="<?php echo esc_attr( 'Enter value', 'approve-orders' ); ?>">
						</div>

						<!-- Value Select -->
						<div class="value-select" style="display:none;">
							<select name="value" class="form-select select-value">
								<option value=""><?php esc_html_e( 'Select a value', 'approve-orders' ); ?></option>
							</select>
						</div>

						<!-- Value Multiselect -->
						<div class="value-multiselect" style="display:none;">
							<select name="value" class="form-select select2-multiselect multiselect-value" multiple>
								<option value=""><?php esc_html_e( 'Select multiple values', 'approve-orders' ); ?></option>
							</select>
						</div>
					</div>

					<!-- Condition Selector -->
					<div class="col-md-1">
						<select class="form-select condition-selector">
							<option value="AND"><?php esc_html_e( ' and ', 'approve-orders' ); ?></option>
							<option value="OR"><?php esc_html_e( ' or ', 'approve-orders' ); ?></option>
						</select>
					</div>

					<!-- Remove Rule Button -->
					<div class="col-md-1 text-end">
						<a href="javascript:void(0)" class="btn btn-sm remove-rule-btn" data-bs-trigger="hover focus" data-bs-container="body" data-bs-toggle="popover" data-bs-content="<?php echo esc_attr( 'Remove Rule', 'approve-orders' ); ?>">
							<i class="dashicons dashicons-remove text-danger"></i>
						</a>
					</div>
				</div>
			</script>
			
				<?php
		}

		if ( ao_fs()->is_paying_or_trial() ) {
			// Attach hook for addons to add Tabs Content dynamically for premium users
			do_action( 'AOFWC_NAV_TABS_CONTENT', $tab );
		}

		echo '</div></div>';
	}

	/**
	 * Sanitize input data
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function sanitize_callback( $input ) {
		return sanitize_post( $input, 'db' );
	}

	/**
	 * Register Custom Order Status
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function register_custom_order_status() {
		register_post_status(
			'wc-awaiting-approval',
			array(
				'label'                     => _x( 'Awaiting Approval', 'Order status', 'approve-orders' ),
				'public'                    => false,
				'exclude_from_search'       => false,
				'show_in_admin_all_list'    => true,
				'show_in_admin_status_list' => true,
				/* translators: %s: count, %s: count */
				'label_count'               => _n_noop( 'Awaiting Approval <span class="count">(%s)</span>', 'Awaiting Approval <span class="count">(%s)</span>', 'approve-orders' ),
			)
		);

		register_post_status(
			'wc-approved',
			array(
				'label'                     => _x( 'Approved', 'Order status', 'approve-orders' ),
				'public'                    => false,
				'exclude_from_search'       => false,
				'show_in_admin_all_list'    => true,
				'show_in_admin_status_list' => true,
				/* translators: %s: count, %s: count */
				'label_count'               => _n_noop( 'Approved <span class="count">(%s)</span>', 'Approved <span class="count">(%s)</span>', 'approve-orders' ),
			)
		);

		register_post_status(
			'wc-rejected',
			array(
				'label'                     => _x( 'Rejected', 'Order status', 'approve-orders' ),
				'public'                    => false,
				'exclude_from_search'       => false,
				'show_in_admin_all_list'    => true,
				'show_in_admin_status_list' => true,
				/* translators: %s: count, %s: count */
				'label_count'               => _n_noop( 'Rejected <span class="count">(%s)</span>', 'Rejected <span class="count">(%s)</span>', 'approve-orders' ),
			)
		);
	}

	/**
	 * Add the custom order status to the list of order statuses.
	 *
	 * @param array $order_statuses The list of order statuses.
	 * @return array The updated list of order statuses.
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	public function add_custom_order_statuses( $order_statuses ) {
		$order_statuses['wc-awaiting-approval'] = _x( 'Awaiting Approval', 'Order status', 'approve-orders' );
		$order_statuses['wc-approved']          = _x( 'Approved', 'Order status', 'approve-orders' );
		$order_statuses['wc-rejected']          = _x( 'Rejected', 'Order status', 'approve-orders' );
		return $order_statuses;
	}

	/**
	 * Add the custom order status column to the admin order list.
	 *
	 * @param array $columns The list of columns.
	 * @return array The updated list of columns.
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	public function add_custom_order_status_column( $columns ) {
		$columns['order_status'] = __( 'Status', 'approve-orders' );
		return $columns;
	}

	/**
	 * Display the custom order status in the admin order list.
	 *
	 * @param string $column The column name.
	 * @return void
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	public function display_custom_order_status_column( $column ) {
		global $post;
		if ( $column === 'order_status' ) {
			$order  = wc_get_order( $post->ID );
			$status = $order->get_status();
			return wc_get_order_status_name( $status );
		}
	}

	/**
	 * Add the pending payment notification email class to the list of email classes.
	 *
	 * @param array $email_classes The list of email classes.
	 * @return array The updated list of email classes.
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	public function add_order_notification_email( $email_classes ) {
		$email_classes['AOFWC_PendingPaymentEmail']   = new AOFWC_PendingPaymentEmail();
		$email_classes['AOFWC_ApprovedOrderEmail']    = new AOFWC_ApprovedOrderEmail();
		$email_classes['AOFWC_RejectedOrderEmail']    = new AOFWC_RejectedOrderEmail();
		$email_classes['AOFWC_AwaitingApprovalEmail'] = new AOFWC_AwaitingApprovalEmail();
		return $email_classes;
	}

	/**
	 * Add the pending payment notification email to the list of email actions.
	 *
	 * @param array $email_actions The list of email actions.
	 * @return array The updated list of email actions.
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	public function add_order_notification_action( $email_actions ) {
		$email_actions[] = 'woocommerce_order_status_pending';
		return $email_actions;
	}

	/**
	 * Send order notification when order status changes to pending, approved, rejected.
	 *
	 * @param int    $order_id The ID of the order.
	 * @param string $old_status The old order status.
	 * @param string $new_status The new order status.
	 * @return void
	 * @since 1.0.0
	 * @version 1.0.0
	 */
	public function send_order_notification( $order_id, $old_status, $new_status ) {

		$current_user_id = get_current_user_id();
		$order           = wc_get_order( $order_id );

		// Valid Approval statuses
		$approval_statuses = array( 'pending', 'approved', 'rejected', 'awaiting-approval', 'cancelled' );

		if ( ! $order || ! $current_user_id || ! in_array( $new_status, $approval_statuses, true ) ) {
			return; // Ensure we have a valid order and user ID
		}

		// Get saved options
		$options         = AOFWC_Settings::get_instance()->get();
		$approved_status = str_replace( 'wc-', '', isset( $options['approved_status'] ) ? $options['approved_status'] : '' );
		$rejected_status = str_replace( 'wc-', '', isset( $options['rejected_status'] ) ? $options['rejected_status'] : '' );

		// Check if the new status matches the configured "approved" status
		if ( $new_status === $approved_status ) {
			// Delete '_rejected_by' meta if it's set before adding '_approved_by'
			$order->delete_meta_data( '_rejected_by' );
			// Add '_approved_by' meta
			$order->add_meta_data( '_approved_by', absint( $current_user_id ), true );
			$order->save();
		}

		// Check if the new status matches the configured "rejected" status
		if ( $new_status === $rejected_status ) {
			// Delete '_approved_by' meta if it's set before adding '_rejected_by'
			$order->delete_meta_data( '_approved_by' );
			// Add '_rejected_by' meta
			$order->add_meta_data( '_rejected_by', absint( $current_user_id ), true );
			$order->save();
		}

		// Check if the new status is 'pending'
		if ( $new_status === 'pending' ) {
			$email = new AOFWC_PendingPaymentEmail();
			$email->trigger( $order_id );
		}

		// Check if the new status is 'approved'
		if ( $new_status === 'approved' ) {
			// Trigger the approved order email
			$email = new AOFWC_ApprovedOrderEmail();
			$email->trigger( $order_id );
		}

		// Check if the new status is 'rejected'
		if ( $new_status === 'rejected' ) {
			// Trigger the rejected order email
			$email = new AOFWC_RejectedOrderEmail();
			$email->trigger( $order_id );
		}

		// Check if the new status is 'awaiting-approval'
		if ( $new_status === 'awaiting-approval' ) {
			$email = new AOFWC_AwaitingApprovalEmail();
			$email->trigger( $order_id );
		}

		// If new status is Cancelled send default WC Cancelled Order Email
		if ( $new_status === 'cancelled' ) {
			$mailer = WC()->mailer();
			$emails = $mailer->get_emails();

			if ( isset( $emails['WC_Email_Cancelled_Order'] ) ) {
				$email = $emails['WC_Email_Cancelled_Order'];
				$email->trigger( $order_id );
			}
		}
	}

	/**
	 * Save Approve Orders Settings
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function save_approve_orders_settings() {

		// Check if the nonce is set and verify it
		if ( ! isset( $_POST['aofwc_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aofwc_nonce'] ) ), 'aofwc_settings_save' ) ) {
			// Nonce is not set or is invalid
			return;
		}

		if ( isset( $_POST['aofwc_option'] ) ) { // phpcs:ignore 												
			$options = sanitize_post( $_POST['aofwc_option'] ); // phpcs:ignore

			$settings = AOFWC_Settings::get_instance();
			$settings->set( wp_unslash( $options ) ); // phpcs:ignore
		}
	}

	/**
	 * Add custom buttons to the order edit page
	 *
	 * @param WC_Order $order The order object.
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function add_buttons_to_order_edit_page( $order ) {

		// Display buttons only for orders with the "pending" status
		if ( ! $order || ! absint( $order->get_id() ) ) {
			return;
		}

		$option     = AOFWC_Settings::get_instance()->get();
		$aofwc_urls = AOFWC_Helper::get_instance()->get_approval_rejection_urls( $order->get_id() );

		$processed_rules = aofwc_process_rules( $order->get_id() );
		$current_user    = wp_get_current_user();

		// Check User with Role or User ID for approval
		if ( isset( $processed_rules['requiresApproval'] ) ) {
			if ( isset( $processed_rules['requiresApproval']['approver_role'] ) ) {
				if ( ! array_intersect( $processed_rules['requiresApproval']['approver_role'], $current_user->roles ) ) {
					return;
				}
			}
			if ( isset( $processed_rules['requiresApproval']['approver_user'] ) ) {
				if ( ! in_array( $current_user->ID, $processed_rules['requiresApproval']['approver_id'], true ) ) {
					return;
				}
			}
		} elseif ( ! array_intersect( $option['default_approver_role'], $current_user->roles ) ) {
			return;
		}

		if ( 'awaiting-approval' === $order->get_status() ) {

			/* translators: %s: approve url, %s: text */
			$approve_button = sprintf(
				'<a href="%s" type="button" class="button aofwc-approve">%s</a>',
				$aofwc_urls['approve_url'],
				esc_html__( 'Approve', 'approve-orders' )
			);

			/* translators: %s: reject url, %s: text */
			$reject_button = sprintf(
				'<a href="%s" type="button" class="button aofwc-reject">%s</a>',
				$aofwc_urls['reject_url'],
				esc_html__( 'Reject', 'approve-orders' )
			);

			echo wp_kses_post( $approve_button . $reject_button );
			return;
		}

		if ( 'pending' === $order->get_status() ) {

			/* translators: %s: reject url, %s: text */
			$reject_button = sprintf(
				'<a href="%s" type="button" class="button aofwc-reject">%s</a>',
				$aofwc_urls['reject_url'],
				esc_html__( 'Reject', 'approve-orders' )
			);

			echo wp_kses_post( $reject_button );
			return;
		}
	}

	/**
	 * Enqueue admin assets
	 *
	 * @since 1.0.0
	 * @version 1.0.0
	 * @return void
	 */
	public function enqueue_assets() {

		$should_localize = false;
		$screen          = get_current_screen();

		// Enqueue Addon JS on User Screen
		if ( $screen && in_array( $screen->id, array( 'user-edit', 'user-new', 'profile' ), true ) ) {
			$should_localize = true;
		}

		// Enqueue Addon JS on Addon Tab
		if ( isset( $_GET['page'] ) && 'approve-orders' === sanitize_text_field( $_GET['page'] ) ) { // phpcs:ignore	
			$should_localize = true;
		}

		if ( $should_localize ) {
			wp_enqueue_style( 'aofwc-bootstrap', AOFWC_URL . 'assets/css/bootstrap.min.css', array(), '5.3.3' );
			// Enqueue SelectWoo script and styles
			wp_enqueue_script( 'selectWoo' );
			wp_enqueue_style( 'selectWoo', WC()->plugin_url() . '/assets/css/select2.css', array(), AOFWC_VERSION );
			// Enqueue admin styles
			wp_enqueue_style( 'aofwc-admin', AOFWC_URL . '/assets/css/admin.css', array(), AOFWC_VERSION );
			wp_enqueue_style( 'aofwc-toastr', AOFWC_URL . 'assets/css/toastr.css', array(), array(), false );
			// Enqueue admin script
			wp_enqueue_script( 'aofwc-bootstrap', AOFWC_URL . 'assets/js/bootstrap.min.js', array( 'jquery' ), '5.3.3', true );
			wp_enqueue_script( 'aofwc-admin', AOFWC_URL . '/assets/js/admin.js', array( 'jquery' ), AOFWC_VERSION );
			wp_enqueue_script( 'aofwc-toast', AOFWC_URL . 'assets/js/toastr.min.js', array( 'jquery' ), null, true );

			// Enqueue Rules JS on Rules Tab
			if ( isset( $_GET['tab'] ) && 'rules' === sanitize_text_field( $_GET['tab'] ) ) { // phpcs:ignore			
				wp_enqueue_script( 'aofwc-rules', AOFWC_URL . 'assets/js/rules.js', array( 'wp-api' ), AOFWC_VERSION, true );
			}

			wp_enqueue_script( 'jquery-ui-core' );
			wp_enqueue_script( 'jquery-ui-sortable' );

			$helper_instance = AOFWC_Helper::get_instance();

			$localized_data = array(
				'nonce'       => wp_create_nonce( 'wp_rest' ),
				'restApiBase' => get_rest_url() . 'aofwc-api/action/',
				'labels'      => array(
					'add_rule' => __( 'Add Rule', 'approve-orders' ),
				),
				'lists'       => array(
					'user_roles'       => $helper_instance->get_roles_list(),
					'payment_gateways' => $helper_instance->get_payment_gateways(),
					'assignee'         => array(
						'line_manager'    => __( 'Line Manager', 'approve-orders' ),
						'second_approver' => __( 'Second Approver', 'approve-orders' ),
					),
				),
			);

			wp_localize_script(
				'aofwc-admin',
				'aofwc_admin_rest',
				$localized_data
			);
		}
	}

	/**
	 * Replace Footer
	 *
	 * @return void
	 * @since 1.0.2
	 */
	public function replace_footer( $text ) {

		if ( isset( $_GET['page'] ) && 'approve-orders' === sanitize_text_field( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$text = __( 'Like Approve Orders for WooCommerce? Give it a', 'approve-orders' );

			$text .= ' <a target="_blank" rel="noopener noreferrer" href="https://wordpress.org/support/plugin/approve-orders/reviews/?rate=5#new-post">';

			$text .= __( '★★★★★', 'aaprove-orders' ) . '</a>' . __( ' rating. A huge thanks in advance!', 'approve-orders' );
		}

		return $text;
	}

	/**
	 * Replace Version
	 *
	 * @return void
	 * @since 1.0.2
	 */
	public function replace_version( $text ) {

		if ( isset( $_GET['page'] ) && 'approve-orders' === sanitize_text_field( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$text = __( 'Version ', 'approve-orders' ) . AOFWC_VERSION;
		}

		return $text;
	}

	/**
	 * Add custom bulk actions
	 *
	 * @param array $bulk_actions The list of bulk actions.
	 * @return array The updated list of bulk actions.
	 * @since 1.0.2
	 * @version 1.0.2
	 */
	public function bulk_actions__premium_only( $bulk_actions ) {
		$bulk_actions['mark_approved']          = __( 'Change status to approved', 'approve-orders' );
		$bulk_actions['mark_awaiting-approval'] = __( 'Change status to awaiting', 'approve-orders' );
		$bulk_actions['mark_rejected']          = __( 'Change status to rejected', 'approve-orders' );
		$bulk_actions['mark_pending']           = __( 'Change status to pending', 'approve-orders' );
		return $bulk_actions;
	}

	/**
	 * Handle custom bulk actions
	 *
	 * @param string $redirect The redirect URL.
	 * @param string $action The action.
	 * @param array  $order_ids The list of order IDs.
	 * @return string The updated redirect URL.
	 * @since 1.0.2
	 * @version 1.0.2
	 */
	public function handle_bulk_actions__premium_only( $redirect, $action, $order_ids ) {

		if ( ! empty( $order_ids ) ) {
			$bulk_action     = str_replace( 'mark_', '', $action );
			$helper_instance = AOFWC_Helper::get_instance();
			foreach ( $order_ids as $order_id ) {
				$helper_instance->update_order_status( $order_id, $bulk_action );
			}
			$redirect = add_query_arg( $action, count( $order_ids ), $redirect );
		}

		return $redirect;
	}

	/**
	 * Show Approver
	 *
	 * @param array $order WooCommerce Order.
	 * @return string The updated redirect URL.
	 * @since 1.0.4
	 * @version 1.0.4
	 */
	public function show_approver__premium_only( $order ) {
		// Get Approver and Rejected By IDs from order meta
		$approved_by = $this->get_user_from_order_meta( $order, '_approved_by' );
		$rejected_by = $this->get_user_from_order_meta( $order, '_rejected_by' );

		// Display approved user if exists
		if ( $approved_by ) {
			$this->display_user_info( $approved_by, 'Approved By' );
		}

		// Display rejected user if exists
		if ( $rejected_by ) {
			$this->display_user_info( $rejected_by, 'Rejected By' );
		}
	}

	/**
	 * Get user from order meta
	 *
	 * @param mixed  $order The order object or order ID.
	 * @param string $meta_key The meta key to retrieve the user ID from.
	 * @return int The user ID if found, otherwise 0.
	 * @since 1.0.4
	 * @version 1.0.4
	 */
	private function get_user_from_order_meta( $order, $meta_key ) {
		if ( $order instanceof \WC_Order ) {
			return absint( $order->get_meta( $meta_key, true ) );
		}
		return 0;
	}

	/**
	 * Display user information
	 *
	 * @param int    $user_id The user ID.
	 * @param string $label The label to display before the user name.
	 * @since 1.0.4
	 * @version 1.0.4
	 */
	private function display_user_info( $user_id, $label ) {
		if ( $user = get_userdata( $user_id ) ) { // phpcs:ignore
			printf(
				'<p><strong>%s:</strong> <a href="%s" target="_blank">%s</a></p>',
				esc_html__( $label, 'approve-orders' ),
				esc_url( get_edit_user_link( $user_id ) ),
				esc_html( $user->display_name )
			);
		}
	}
}
