<?php // phpcs:ignore WordPress.Files.FileName

defined( 'ABSPATH' ) || exit;

/**
 * Class YITH_COG_Orders
 *
 * @class      YITH_COG_Orders
 * @package    Yithemes
 * @since      Version 1.0.0
 * @author     YITH <plugins@yithemes.com>
 */

if ( ! class_exists( 'YITH_COG_Orders' ) ) {
	/**
	 * Class YITH_COG_Orders
	 */
	class YITH_COG_Orders {

		/**
		 * * Single instance of the class
		 *
		 * @var YITH_COG_Orders
		 */
		protected static $instance = null;

		/**
		 * Construct
		 *
		 * @since 1.0
		 */
		public function __construct() {

			// set the order meta when an order is placed from standard checkout.
			add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'set_order_cost_meta' ), 10, 1 );

			add_action( 'woocommerce_new_order', array( $this, 'set_order_cost_meta' ), 10, 1 );
			add_action( 'woocommerce_update_order', array( $this, 'set_order_cost_meta' ), 10, 1 );

            // update the item cost in the wc_order_product_lookup table.
			add_action( 'woocommerce_analytics_update_product', array( $this, 'update_item_cost_with_analytics_update' ) );

			if ( defined( 'YITH_YWRAQ_PREMIUM' ) ) {
				add_action( 'ywraq_after_create_order', array( $this, 'set_order_cost_meta' ), 10, 1 );
			}

			// Show the CoG in the order.
			add_action( 'woocommerce_admin_order_item_headers', array( $this, 'yith_cog_order_item_header' ) );
			add_action( 'woocommerce_admin_order_item_values', array( $this, 'yith_cog_order_item_value' ), 10, 3 );

			add_action( 'woocommerce_admin_order_totals_after_total', array( $this, 'yith_cog_show_order_total_cost' ) );

		}

		/**
		 * Returns single instance of the class
		 *
		 * @return stdClass
		 * @var YITH_COG_Orders instance
		 */
		public static function get_instance() {
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}


		/** Set necessary values when an order has been placed ************************/

		/**
		 * Set the cost of goods item meta for a order.
		 *
		 * @param int $order_id Order ID.
		 */
		public function set_order_cost_meta( int $order_id ) {
			
			$order            = wc_get_order( $order_id );
			$cost_already_set = $order->get_meta( 'yith_cog_set' );

			if ( ! is_object( $order ) || 'yes' === $cost_already_set ) {
				return;
			}

			$this->set_order_cost_meta_overriding( $order_id );
		}

		/**
		 * Set the cost of goods item meta for a order.
		 *
		 * @param int $order_id Order ID.
		 */
		public function set_order_cost_meta_overriding( $order_id ) {

			$order      = wc_get_order( $order_id );
			$total_cost = 0;

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

			$order_items = $order->get_items();

			if ( empty( $order_items ) ){
				return;
			}
			
			foreach ( $order_items as $item_id => $item ) {

				$product_id = ( ! empty( $item['variation_id'] ) ) ? $item['variation_id'] : $item['product_id'];
				$product    = wc_get_product( $product_id );

				if ( ! is_object( $product ) ) {
					continue;
				}

				if ( $product->is_type( 'gift-card' ) ) {
					continue;
				}

				/**
				 * APPLY_FILTERS: yith_cog_set_order_item_cost_meta
				 *
				 * Filter the item cost of goods saved in the order item meta.
				 *
				 * @param float $item_cost the item cost
				 * @param array $item the item array
				 * @param float $order the order object
				 *
				 * @return float
				 */
				$item_cost = apply_filters( 'yith_cog_set_order_item_cost_meta', get_cost( $product ), $item, $order );
				$quantity  = $item['qty'];

				if ( '' === $item_cost ) {
					$item_cost = 0;
				}

				// Integration with YITH Bundle: if the product is inside a bundle, dont add it to the report
				$is_bundle = wc_get_order_item_meta( $item_id, '_bundled_by' );

				if ( $is_bundle ){
					$this->set_item_cost_meta( $item_id, 0, $quantity );
					continue;
				}

				$this->set_item_cost_meta( $item_id, $item_cost, $quantity );
				$this->set_item_taxes( $order_id );

				// order total cost
				$total_cost += ( $item_cost * $quantity );

				// update also the lookup table
				$this->update_item_cost_with_analytics_update( $item_id );

			}
			/**
			 * APPLY_FILTERS: yith_set_order_cost_meta
			 *
			 * Filter the order cost of goods total saved in the order meta.
			 *
			 * @param float $total_cost the order total cost
			 * @param float $order the order object
			 *
			 * @return float
			 */
			$total_cost = apply_filters( 'yith_set_order_cost_meta', $total_cost, $order );

			$formatted_total_cost = wc_format_decimal( $total_cost, wc_get_price_decimals() );

			$order->update_meta_data( '_yith_cog_order_total_cost', $formatted_total_cost );
			$order->update_meta_data( 'yith_cog_set', 'yes' );
			$order->save();
		}
        
		/**
		 * Update the item data in the yith_cog_sales_report_data table, getting the info from the wc_order_product_lookup when it's updated
		 *
		 * @param int $item_id Item ID.
		 */
		public function update_item_cost_with_analytics_update( $item_id ) {

			global $wpdb;

			$product_lookup_table = $wpdb->prefix . 'wc_order_product_lookup';
			$plugin_data_table    = $wpdb->prefix . 'yith_cog_sales_report_data';

			$new_row_lookup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $product_lookup_table WHERE order_item_id = %d", $item_id ), ARRAY_A );

            // check if the new row contains data, it should be an array to be able to insert the row in the custom table
            if ( isset( $new_row_lookup ) && is_array( $new_row_lookup ) ) {

	            $row_in_plugin_data_table = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $plugin_data_table WHERE order_item_id = %d", $item_id ), ARRAY_A );

	            if ( ! isset( $row_in_plugin_data_table ) ) {
		            // Insert it in our custom table
		            $wpdb->insert( $plugin_data_table, $new_row_lookup );
	            }

	            $item_cost = wc_get_order_item_meta( $item_id, '_yith_cog_item_cost' );

	            if ( $item_cost > 0 ){
		            $wpdb->update( $plugin_data_table, array( 'item_cost' => $item_cost ), array( 'order_item_id' => $item_id) );
	            }
            }
			
		}


		/**
		 * Set an item's taxes.
		 *
		 * @param int $order_id Order ID.
		 */
		protected function set_item_taxes( $order_id ) {
			$order = wc_get_order( $order_id );

			foreach ( $order->get_items() as $item_id => $item ) {

				$item_tax = $order->get_item_tax( $item );

				wc_update_order_item_meta( $item_id, '_yith_cog_item_tax', $item_tax );

			}
		}

		/**
		 * Set an item's cost meta.
		 *
		 * @param int $item_id Item ID.
		 * @param int $item_cost Item cost.
		 * @param int $quantity Quantity.
		 */
		protected function set_item_cost_meta( $item_id, $item_cost, $quantity ) {

			$formatted_cost  = wc_format_decimal( $item_cost );
			$formatted_total = wc_format_decimal( $item_cost * $quantity );
            
			wc_update_order_item_meta( $item_id, '_yith_cog_item_cost', $formatted_cost );
			wc_update_order_item_meta( $item_id, '_yith_cog_item_total_cost', $formatted_total );

			wp_cache_delete( $item_id, 'order_item_meta' );
		}

		/** Render the COG in the order ************************/

		/**
		 * COG Column in the Order.
		 */
		public function yith_cog_order_item_header() {
			?>
			<th class="item_cog sortable" data-sort="float"><?php echo esc_html__( 'Cost of Goods', 'yith-cost-of-goods-for-woocommerce' ); ?></th>
			<?php
		}


		/**
		 * COG Value in the Order.
		 *
		 * @param object $product Product.
		 * @param object $item Order item.
		 * @param int    $item_id Item ID.
		 */
		public function yith_cog_order_item_value( $product, $item, $item_id ) {

			$cost = wc_get_order_item_meta( $item_id, '_yith_cog_item_cost', true );

			/**
			 * APPLY_FILTERS: yith_cog_convert_amounts_order_item_value
			 *
			 * Filter the order item cost of goods value, to allow third-party currency conversions.
			 *
			 * @param float $cost the order item cost
			 * @param int $item_id the item ID
			 *
			 * @return float
			 */
			$cost_converted = apply_filters( 'yith_cog_convert_amounts_order_item_value', $cost, $item_id );

			if ( $cost_converted > 0 ) {
				?>
				<td class="item_cost" data-sort-value="<?php echo esc_attr( $cost_converted ); ?>" width="1%">
					<div class="view">
						<?php
						/**
						 * APPLY_FILTERS: yith_cog_item_cost_display_value
						 *
						 * Filter the order item cost of goods value displayed in the order.
						 *
						 * @param string the order item cost formatted
						 * @param int $cost the order item cost
						 * @param string $cost_converted the order item cost formatted
						 *
						 * @return float
						 */
						?>
						<span><?php echo wp_kses_post( apply_filters( 'yith_cog_item_cost_display_value', wc_price( $cost_converted ), $cost, $cost_converted ) ); ?></span>
					</div>
				</td>
				<?php
			} else {
				?>
				<td class="item_cost" data-sort-value="-" width="1%">
					<div class="view">
						<span> - </span>
					</div>
				</td>
				<?php
			}
		}

		/**
		 * Order COG Value in the Order totals.
		 *
		 * @param int $order_id Order ID.
		 */
		public function yith_cog_show_order_total_cost( $order_id ) {

			$order = wc_get_order( $order_id );
			if ( is_object( $order ) ) {
				$order_total_cost = $order->get_meta( '_yith_cog_order_total_cost' );
			}

			/**
			* APPLY_FILTERS: yith_cog_convert_amounts_order_total
			*
			* Filter the order total cost of goods value, to allow third-party currency conversions.
			*
			* @param float $cost the order item cost
			* @param int $item_id the item ID
			*
			* @return float
			*/
			$order_total_cost_converted = apply_filters( 'yith_cog_convert_amounts_order_total', $order_total_cost, $order_id );
			?>
			<tr>
				<td class="label"><?php echo 'Cost of Goods'; ?>:</td>
				<td width="1%"></td>
				<?php
				/**
				 * APPLY_FILTERS: yith_cog_order_total_cost_display_value
				 *
				 * Filter the order total cost of goods value displayed in the order.
				 *
				 * @param string the order total cost formatted
				 * @param int $order_total_cost the order total cost
				 * @param string $order_total_cost_converted the order total cost formatted
				 *
				 * @return float
				 */
				?>
				<td class="total"><?php echo wp_kses_post( apply_filters( 'yith_cog_order_total_cost_display_value', wc_price( $order_total_cost_converted ), $order_total_cost, $order_total_cost_converted ) ); ?></td>
			</tr>
			<?php
		}

	}
}
