<?php

namespace Bright_Deposits_For_WooCommerce\Pages;

use Bright_Deposits_For_WooCommerce\Core\ContainerManager;

/**
 * @package Bright_Deposits_For_WooCommerce\Pages
 * @since 1.0.0
 * @author Bright Plugins
 * Description: This class is responsible for handling the order page functionalities for deposits in WooCommerce.
 */
class Order {
	
	/**
	 * Singleton instance of the class.
	 */
	private static $instance = null;

	protected $helper;

	public function __construct() {

		$this->helper = ContainerManager::get('helper');

		add_filter( 'woocommerce_order_item_quantity_html', [$this, 'displayItemDepositData'], 20, 2 );
		add_filter( 'woocommerce_order_actions', [$this, 'addOrderAction'], 10, 2 );
		add_filter( 'woocommerce_get_order_item_totals', [$this, 'tableRowData'], 10, 2 );
		add_action( 'woocommerce_admin_order_totals_after_tax', [$this, 'displayDepositDataOrderDetails'], 20, 1 );
		add_action( 'woocommerce_admin_order_preview_end', [$this, 'previewDepositData'] );
		add_action( 'woocommerce_admin_order_item_headers', [$this, 'adminOrderItemsHeaders'], 10, 1 );
		add_action( 'woocommerce_admin_order_item_values', [$this, 'adminOrderItemsValues'], 10, 3 );
		add_action( 'add_meta_boxes', [$this, 'depositMetaBox'], 10, 2 );
		add_action( 'woocommerce_after_order_details', [$this, 'customerDepositDetails'], 20, 1 );
		add_action( 'woocommerce_order_details_after_order_table', [$this, 'woocommerceOrderAgainButton'], 10, 1 );
		add_action( 'woocommerce_order_action_deposit_reminder', [$this, 'actionDepositReminder'], 10, 1 );
		add_filter( 'wc_order_is_editable', [$this, 'OrderStatusEditable'], 10, 2 );
		add_filter( 'woocommerce_admin_order_preview_get_order_details', [$this, 'addDepositDetails'], 10, 2 );
		add_action( 'woocommerce_order_details_after_order_table', [$this, 'maybe_remove_order_again_button'], 19, 1 );
		add_filter( 'woocommerce_get_formatted_order_total', [$this, 'customTotalFormatThankyou'], 10, 2 );
		add_action( 'woocommerce_admin_order_list_table_column_value', [$this, 'customOrdersTotalDisplay'], 10, 2);
		add_filter( 'manage_woocommerce_page_wc-orders_columns', [$this, 'addNewColumnDeposit'], 99);
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', [$this, 'depositOrderTotalDisplay'], 99, 2);
		add_action( 'woocommerce_order_status_changed', [$this, 'sendNotificationFullyPaidDeposit'], 10, 4 );
	}
	
	/**
	 * Get the singleton instance of the class.
	 * @since 1.0.0
	 * @return Order
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Prevents cloning of the instance.
	 * @since 1.0.0
	 * @return void
	 */
	private function __clone() {
		// Cloning is forbidden.
	}

	/**
	 * Prevents unserializing of the instance.
	 * @since 1.0.0
	 * @return void
	 */	
	public function __wakeup() {
		// Unserializing instances of this class is forbidden.
	}

	/**
	 * add deposit data into the array for display as preview
	 * @since 1.0.0
	 * @param array $data
	 * @param \WC_Order $order
	 * @return array
	 */
	public function addDepositDetails( $data, $order ) {
		$data['depositPaid'] = ( !empty( $order->get_meta( '_deposit_value', true ) ) ) ? wc_price( $order->get_meta( '_deposit_value', true ) ) : '-';
		$data['depositDue']  = ( !empty( $order->get_meta( '_deposit_value', true ) ) ) ? wc_price( $order->get_total() - $order->get_meta( '_deposit_value', true ) ) : '-';
		return $data;
	}

	/**
	 * Display deposit data in the order preview.
	 * @since 1.0.0
	 * @return void
	 */
	public function previewDepositData() {
		?>
		
        <div class="wc-order-preview-deposit">
            <h2><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_deposit_payment_details_label' ) ); ?></h2>
            <div>
                <strong><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_paid_label' ) ); ?>:</strong>
                {{{ data.depositPaid }}}
            </div>
            <div>
                <strong><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_due_payment_label' ) ); ?>:</strong>
                {{{ data.depositDue }}}
            </div>
        </div>

    	<?php 
	}

	/**
	 * when reminder action is trigger
	 *
	 * @param  object $order
	 * @return void
	 */
	public function actionDepositReminder( $order ) {

		$args = array(
			'post_type'   => 'shop_deposit',
			'post_status' => 'wc-pending',
			'post_parent' => $order->get_id(),
		);

		$DueOrders = get_children( $args );
		foreach ( $DueOrders as $key => $value ) {
			if ( ! is_object( $value ) || ! isset( $value->ID ) ) {
				continue;
			}
			do_action( 'bright_deposits_admin_next_payment_reminder_notification', $value->ID, $order );
			do_action( 'bright_deposits_customer_next_payment_reminder_notification', $value->ID, $order );
		}
		// Note the event.
		$order->add_order_note( $this->helper->getOptionValue( 'bdfw_reminder_sent_note' ), false, true );

	}

	/**
	 * Add reminder acition to deposit order area
	 *
	 * @param  array  $actions
	 * @return array
	 */
	public function addOrderAction( $actions, $order ) {

		if ( ! $order ) {
			return $actions;
		}

		if ( $order->get_meta('_deposit_value', true) ) {
			$actions['deposit_reminder'] = $this->helper->getOptionValue( 'bdfw_send_reminder_notification_label' );
		}
		return $actions;
	}

	/**
	 * Make deposit order status editable as like the pending payment status
	 * @since 1.0.0
	 * @param  string $editable
	 * @param  object $order
	 * @return bool
	 */
	public function OrderStatusEditable( $editable, $order ) {
		if ( $order->get_status() == 'deposit' ) {
			$editable = true;
		}

		/**
		 * BDFWBP_CUSTOM_FILTER_HOOK: Allows developers to modify the deposit order status editable.
		 * @since 1.0.0
		 * @param bool $editable
		 * @param \WC_Order $order
		 * @return bool
		 */
		return apply_filters( 'bdfwbp_order_status_editable', $editable, $order );
	}

	/**
	 * Remove the order again button for deposit orders.
	 * @since 1.0.0
	 * @param \WC_Order $order
	 * @return void
	 */
	public function maybe_remove_order_again_button( $order ) {
		if ( $this->helper->isDepositOrder( $order->get_id() ) ) {
			remove_action( 'woocommerce_order_details_after_order_table', 'woocommerce_order_again_button', 20 );
		}
	}

	/**
	 * Display an 'order again' button on the view order page.
	 * @since 1.0.0
	 * @param \WC_Order $order
	 * @return void
	 */
	public function woocommerceOrderAgainButton( $order ) {
		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code before displaying the order again button.
		 * @since 1.0.0
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_before_woocommerce_order_again_button', $order );

		if ( !$order || !$order->has_status( apply_filters( 'woocommerce_valid_order_statuses_for_order_again', array( 'completed' ) ) ) || !is_user_logged_in() ) {
			return;
		}

		$depositId = $order->get_meta( '_deposit_id', true );

		if ( !empty( $depositId ) ) {
			return;
		}

		wc_get_template(
			'order/order-again.php',
			array(
				'order'           => $order,
				'order_again_url' => wp_nonce_url( add_query_arg( 'order_again', $order->get_id(), wc_get_cart_url() ), 'woocommerce-order_again' ),
			)
		);

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code after displaying the order again button.
		 * @since 1.0.0
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_after_woocommerce_order_again_button', $order );
	}

	/**
	 * Display deposit data on the order page.
	 * @since 1.0.0
	 * @param \WC_Order $order
	 * @return void
	 */
	public function customerDepositDetails( $order ) {

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code before displaying the customer deposit details.
		 * @since 1.0.0
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_before_customer_deposit_details', $order );

		if ( empty( $order->get_meta( '_deposit_value', true ) ) ) {
			return; // hide summary for non deposit orders
		}

		wc_get_template( 'order/deposit-summary.php', array( 'order' => $order ), '', BDFWBP_TEMPLATE_PATH );

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code after displaying the customer deposit details.
		 * @since 1.0.0
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_after_customer_deposit_details', $order );
	}

	/**
	 * Add metabox in order post type
	 * @since 1.0.0
	 * @param string $page
	 * @param \WC_Order $order
	 * @return void
	 */
	public function depositMetaBox($page, $order) {
		
		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code before displaying the deposit meta box.
		 * @since 1.0.0
		 * @param string $page
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_before_deposit_meta_box', $page, $order );
		
		if ( $page == 'woocommerce_page_wc-orders' ) {
			if ( empty( $order->get_meta( '_deposit_value', true ) ) ) {
				return; // return if not deposit
			}

			add_meta_box(
				'bdfwbp_deposit_orders',
				$this->helper->getOptionValue( 'bdfw_deposit_payments_label' ),
				[$this, 'childOrdersTable'],
				'woocommerce_page_wc-orders',
				'normal',
				'high'
			);
		}
		else{
			return; // return if not order type
		}

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code after displaying the deposit meta box.
		 * @since 1.0.0
		 * @param string $page
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_after_deposit_meta_box', $page, $order );
	}
	
	/**
	 * Add markup to show deposit orders
	 * @since 1.0.0
	 * @param \WC_Order $order
	 * @return void
	 */
	public function childOrdersTable($order) {

		$args = array(
			'type'   => 'shop_deposit',
			'parent' => $order->get_id(),
		);

		$depositList = wc_get_orders( $args );?>

        <table class="wp-list-table widefat fixed striped table-view-excerpt ">
        <thead>

            <tr>
            <th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_order_number_label' ) ); ?></th>
            <th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_relationship_label' ) ); ?></th>
            <th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_date_label' ) ); ?></th>
            <th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_payment_label' ) ); ?></th>
            <th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_status_label' ) ); ?></th>
            <th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_total_label' ) ); ?></th>
			<th><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_next_payment_date_label' ) ); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ( $depositList as $key => $deposit ) {
			$depositOrder = $deposit; // wc_get_orders already returns order objects.
			if ( $depositOrder->get_status() == 'completed' ) {
				$paymentStatus = $this->helper->getOptionValue( 'bdfw_deposit_label' );
			} else {
				$paymentStatus = $this->helper->getOptionValue( 'bdfw_due_payment_label' );
			}?>
                    <tr>
					<td><?php echo '<a href="' . esc_url( admin_url( 'post.php?post=' . $depositOrder->get_id() . '&action=edit' ) ) . '" class="order-view"><strong>#' . esc_html( $depositOrder->get_id() ) . '</strong></a>'; ?></td>
                    <td><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_deposit_payment_label' ) ); ?></td>

                    <td>
						<?php 
							$order_date = $depositOrder->get_date_created();
							$order_timestamp = $order_date ? $order_date->getTimestamp() : '';

							if ( ! $order_timestamp ) {
								echo '&ndash;';
							} else {
								// Check if the order was created within the last 24 hours, and not in the future.
								if ( $order_timestamp > strtotime( '-1 day', time() ) && $order_timestamp <= time() ) {
									$show_date = sprintf(
										/* translators: %s: human-readable time difference */
										_x( '%s ago', '%s = human-readable time difference', 'bright-deposits-for-woocommerce' ),
										human_time_diff( $depositOrder->get_date_created()->getTimestamp(), time() )
									);
								} else {
									$show_date = $depositOrder->get_date_created()->date_i18n( apply_filters( 'woocommerce_admin_order_date_format', __( 'M j, Y', 'bright-deposits-for-woocommerce' ) ) );
								}
								printf(
									'<time datetime="%1$s" title="%2$s">%3$s</time>',
									esc_attr( $depositOrder->get_date_created()->date( 'c' ) ),
									esc_html( $depositOrder->get_date_created()->date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ) ),
									esc_html( $show_date )
								);
							}
						?>
					</td>

                    <td><?php echo esc_html( $paymentStatus ); ?></td>

                    <td>
                    <?php $depositStatus = $depositOrder->get_status(); // order status ?>
                    <?php echo sprintf( '<mark class="order-status %s tips"><span>%s</span></mark>', esc_attr( sanitize_html_class( 'status-' . $depositStatus ) ), esc_html( wc_get_order_status_name( $depositStatus ) ) ); ?>
                    </td>

                    <td><?php echo wp_kses_post(wc_price( $depositOrder->get_total() )); ?></td>
					<td>
						<?php 
							if ( $depositOrder->get_status() == 'pending' ) {
        						$next_payment_date = $this->helper->getNextPaymentDate($order);
								echo esc_html( $next_payment_date );
							}
						?>
					</td>

                    </tr>

        <?php }?>

        </tbody>
        </table>
    	<?php 
	}

	/**
	 * Add order backend table headers
	 * @since 1.0.0
	 * @param  object $order
	 * @return void
	 */
	public function adminOrderItemsHeaders( $order ) {

		if ( $this->helper->isDepositOrder( $order->get_id() ) == false ) {
			return;
		}

		?>
        <th class="line-deposit sortable" data-sort="float"><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_deposit_label' ) ); ?></th>
        <th class="line-due-paymnet sortable" data-sort="float"><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_due_label' ) ); ?></th>
    	<?php 
	}

	/**
	 * Display Order backendend deposit value
	 * @since 1.0.0
	 * @param  object $product
	 * @param  array  $item
	 * @param  int    $item_id
	 * @return void
	 */
	public function adminOrderItemsValues( $product, $item, $item_id ) {

		if ( null == $product ) {
			echo '<td class="item_cost" width="1%">&nbsp;</td><td class="quantity" width="1%">&nbsp;</td>';
			return;
		}

		$initial_payment_total = $item['_deposit'];
		$future_payment_total     = $item['_due_payment'];

		if ( null == $initial_payment_total ) {
			return;
		}

		?>

        <td class="line-deposit" width="1%">

            <?php if ( $product && $initial_payment_total ) {?>
                <div class="view">
                    <?php echo wp_kses_post(wc_price( $initial_payment_total )); ?>
                </div>
                <div class="edit" style="display: none;">
                    <input type="text" disabled="disabled" name="deposit[<?php echo absint( $item_id ); ?>]"
                            placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" value="<?php echo esc_attr( round( $initial_payment_total, wc_get_price_decimals() ) ); ?>"
                            class=" wc_input_price" data-total="<?php echo esc_attr( round( $initial_payment_total, wc_get_price_decimals() ) ); ?>"/>
                </div>
            <?php }?>
        </td>
        <td class="deposit-due-paymnet" width="1%">

            <?php if ( $product && $initial_payment_total ) {?>
                <div class="view">
                    <?php echo wp_kses_post(wc_price( $future_payment_total )); ?>
                </div>
                <div class="edit" style="display: none;">
                    <input type="text" disabled="disabled" name="due_payment[<?php echo absint( $item_id ); ?>]"
                            placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" value="<?php echo esc_attr( round( $future_payment_total, wc_get_price_decimals() ) ); ?>"
                            class="due_payment wc_input_price" data-total="<?php echo esc_attr( round( $future_payment_total, wc_get_price_decimals() ) ); ?>"/>
                </div>
            <?php }?>
        </td>
    	<?php 
	}

	/**
	 * Add deposit Table data in order details / Email template
	 * @since 1.0.0
	 * @param array $total_rows
	 * @param \WC_Order $order
	 * @return array
	 */
	public function tableRowData( $total_rows, $order ) {
		if ( empty( $order->get_meta( '_deposit_value', true ) ) ) {
			return $total_rows;
		}

		$deposit_amount_total = 0;

		foreach ( $order->get_items() as $item ) {
			$deposit      = $item->get_meta('_deposit');
			if ( isset($deposit) && !empty($deposit) ) {
				$quantity = $item->get_quantity();
				$deposit_amount_total += $deposit * $quantity;
			}
			else{
				$quantity = $item->get_quantity();
				$deposit_amount_total += $item->get_total() * $quantity;
			}
		}

		$deposit_amount = wc_price( $deposit_amount_total );

		$total_rows['cart_subtotal']['value'] = $deposit_amount;
		$total_rows['order_total']['value'] = apply_filters( 'woocommerce_deposit_to_pay_html', wc_price( $order->get_meta( '_deposit_value', true ) ) );

		$total_rows['due_payment'] = array(
			'label' => $this->helper->getOptionValue( 'bdfw_due_payment_label' ).':',
			'value' => apply_filters( 'bdfwbp_due_payment_html', wc_price( $order->get_meta( '_due_payment_value', true ) ) )
		);

        $next_payment_date = $this->helper->getNextPaymentDate($order);

		$total_rows['next_payment_date'] = array(
			'label' => $this->helper->getOptionValue( 'bdfw_next_payment_date_label' ).':',
			'value' => $next_payment_date,
		);

		/**
		 * BDFWBP_CUSTOM_FILTER_HOOK: Allows developers to modify the order table row data shown in the order details page and email template.
		 * @since 1.0.0
		 * @param array $total_rows
		 * @param \WC_Order $order
		 * @return array
		 */
		return apply_filters( 'bdfwbp_order_table_row_data', $total_rows, $order );
	}

	/**
	 * Display the deposit data in the order details totals table. [for admin]
	 * @since 1.0.0
	 * @param int $order_id
	 * @return void
	 */
	public function displayDepositDataOrderDetails( $order_id ) {
		$order = wc_get_order( $order_id );

		if( !$order instanceof \WC_Order ) {
			return;
		}

		$initial_payment_total = $order->get_meta( '_deposit_value', true );

		if ( empty( $initial_payment_total ) ) {
			return;
		}

		$future_payment_total = $order->get_meta( '_due_payment_value', true );
		do_action( 'bdfwbp_before_deposit_data_display_table_tr', $order_id );
		?>
        <tr>
			<td class="label"><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_deposit_label' ) ); ?>:</td>

			<td width="1%"></td>
			<td class="total">
				<?php echo wp_kses_post(wc_price( $initial_payment_total )); ?>
			</td>
        </tr>
        <tr>
			<td class="label"><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_due_amount_label' ) ); ?>:</td>
			<td width="1%"></td>
			<td class="total">
				<?php echo wp_kses_post(wc_price( $future_payment_total )); ?>
			</td>
		</tr>
    	<?php

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code after displaying the deposit data in the order details totals table [for admin].
		 * @since 1.0.0
		 * @param \WC_Order $order
		 * @return void
		 */
		do_action( 'bdfwbp_after_deposit_data_display_table_tr', $order );
	}

	/**
	 * Display deposit data below the cart item in order review section
	 * @since 1.0.0
	 * @param string $quantity
	 * @param array $item
	 * @return string
	 */
	public function displayItemDepositData( $quantity, $item ) {
		if ( isset( $item['_deposit'] ) ) {
			$initial_payment_total = $item['_deposit'] * $item['quantity'];
			$future_payment_total     = $item['_due_payment'] * $item['quantity'];
			$deposit_data_html = sprintf(
				'<p>' . $this->helper->getOptionValue( 'bdfw_deposit_label' ) . ' %s <br> ' . $this->helper->getOptionValue( 'bdfw_due_payment_label' ) . ' %s</p>',
				wc_price( $initial_payment_total ),
				wc_price( $future_payment_total )
			);
			
			/**
			 * BDFWBP_CUSTOM_FILTER_HOOK: Allows developers to modify the deposit data html below the cart item in order review section.
			 * @since 1.0.0
			 * @param string $deposit_data_html
			 * @param array $item
			 * @return string
			 */
			$quantity .= apply_filters( 'bdfwbp_order_item_deposit_data_html', $deposit_data_html, $item );
		}

		return $quantity;
	}

	/**
	 * Custom total format for thank you page
	 * @since 1.0.0
	 * @param string $formatted_total
	 * @param \WC_Order $order
	 * @return string
	 */
	public function customTotalFormatThankyou( $formatted_total, $order ) {
		if ( is_wc_endpoint_url( 'order-received' ) ) {
			$deposit_value = $order->get_meta( '_deposit_value', true );

			if ( $deposit_value ) {
				$formatted_total = wc_price( $deposit_value );
			}
		}
		return $formatted_total;
	}

	/**
	 * Add new column for deposit in order list table
	 * @since 1.0.0
	 * @param array $columns
	 * @return array
	 */
    public function addNewColumnDeposit($columns) {
        $columns['bdfwbp_deposit'] = 'Deposit';
        return $columns;
    }

	/**
	 * Display deposit total in order list table
	 * @since 1.0.0
	 * @param string $column
	 * @param int $post_id
	 * @return void
	 */
    public function depositOrderTotalDisplay($column, $post_id) {
		// get the order
		$order = wc_get_order( $post_id );

		// if the order is not an instance of \WC_Order, return
		if( !$order instanceof \WC_Order ){
			return;
		}

		if ($column === 'bdfwbp_deposit') {
			$status = $order->get_status();
        	$deposit = $order->get_meta('_deposit_value', true);

			// if the deposit is empty, return
			if( empty($deposit) ){
				return;
			}

			$statuses_compatible_deposits = array('partially-paid');
			$status_paid_deposits = array('processing', 'completed');
			
			if ( in_array($status, $statuses_compatible_deposits ) ) {
        		$next_payment_date = $this->helper->getNextPaymentDate($order);

				echo '<strong>'.wp_kses_post(wc_price($deposit)).'</strong> <small>(of ' . wp_kses_post(wc_price($order->get_total())) . ')</small>';
				echo '<br>';
				echo '<small>' . esc_html($this->helper->getOptionValue( 'bdfw_next_payment_date_label' )) . ': <strong>' . esc_html($next_payment_date) . '</strong></small>';
			}
			else if( in_array($status, $status_paid_deposits) ){
				echo '<strong>'.esc_html($this->helper->getOptionValue( 'bdfw_full_payment_label' )).'</strong>';
			}	
        }
    }

	/**
	 * Send notification for fully paid deposits.
	 *
	 * @param int $order_id
	 * @param string $old_status
	 * @param string $new_status
	 * @param WC_Order $order
	 * @return void
	 */
	public function sendNotificationFullyPaidDeposit( $order_id, $old_status, $new_status, $order ) {
		if ( $new_status === 'completed' ) {
			// Check if the order is related to deposits
			$is_deposit_order = $this->helper->isDepositOrder( $order_id );
			$is_deposit_child_order = 'shop_deposit' === $order->get_type();

			if ( $is_deposit_order && !$is_deposit_child_order && $old_status === 'processing' ) {
				// Get the mailer instance
				$mailer = WC()->mailer()->get_emails();

				// Trigger the email for the customer
				if ( isset( $mailer['WC_Customer_Fully_Paid_Deposit'] ) ) {
					$mailer['WC_Customer_Fully_Paid_Deposit']->trigger( $order_id, $order );
				}

				// Trigger the email for the admin
				if ( isset( $mailer['WC_Admin_Fully_Paid_Deposit'] ) ) {
					$mailer['WC_Admin_Fully_Paid_Deposit']->trigger( $order_id, $order );
				}
			}	
		}
	}

}
