<?php
/**
 * Class to show offer contribution in the order.
 *
 * @package   smart-offers/includes/admin/
 * @since     3.7.0
 * @version   1.1.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SO_Admin_Order_Contribution' ) ) {

	Class SO_Admin_Order_Contribution {

		public function __construct() {
			add_action( 'admin_enqueue_scripts', array( $this, 'sa_css_on_orders_dashboard' ) );
			add_filter( 'woocommerce_get_formatted_order_total', array( $this, 'show_offer_contribution_in_order_dashboard' ), 999, 2 );
		}

		public function sa_css_on_orders_dashboard() {
			if ( false === so_is_admin_orders_screen() ) {
				return;
			}

			$plugin_data = SA_Smart_Offers::get_smart_offers_plugin_data();
			$version = $plugin_data['Version'];
			wp_register_style( 'so_admin_orders_style', plugins_url(SMART_OFFERS) . '/assets/css/so-admin-orders-dashboard.css', array(), $version );
			wp_enqueue_style( 'so_admin_orders_style' );

		}

		public function show_offer_contribution_in_order_dashboard( $total, $order = null ) {
			if ( false === so_is_admin_orders_screen() || ( ! $order instanceof WC_Order ) ) {
				return $total;
			}

			$order_status       = ( is_callable( array( $order, 'get_status' ) ) ) ? $order->get_status() : '';
			$valid_order_status = array( 'on-hold', 'processing', 'completed' );
			if ( empty( $order_status ) || ! in_array( $order_status, $valid_order_status )  ) {
				return $total;
			}

			$so_meta_data = $order->get_meta( 'smart_offers_meta_data', true );

			$so_contribution = array();
			if ( ! empty( $so_meta_data ) && is_array( $so_meta_data ) ) {
				foreach ( $so_meta_data as $so_meta ) {
					array_push( $so_contribution, $so_meta['offered_price'] );
				}
			}

			$so_total = '';
			if ( ! empty( $so_contribution ) && is_array( $so_contribution ) ) {
				$so_total = array_sum( $so_contribution );
			}

			if ( empty( $so_total ) ) {
				return $total;
			}

			$order_currency = ( is_callable( array( $order, 'get_currency' ) ) ) ? $order->get_currency() : get_woocommerce_currency();
			$html  = '</span><br/>
			<div class="so_contribution"><span class="tips" data-tip="' . esc_attr__( 'Smart Offers contribution in this order.', 'smart-offers' ) . '"><img class="so_trendline" src='.SO_PRE_URL.'assets/images/trendline_green_up.png><em> ' . sprintf( esc_html__( '%s' ), wc_price( $so_total, array( 'currency' => $order_currency ) ) ) . '</em></span></div>';
				$total = $total . $html;

			return $total;
		}

	}

	return new SO_Admin_Order_Contribution();
}
