<?php
/**
 * Elite Notification Woocommerce Source
 *
 * @package Elite_Notification_Lite\Source
 */

namespace Elite_Notification_Lite\Source;

use Appsbd_Lite\V4\libs\AppInput;
use Elite_Notification_Lite\Core\Elite_Notification_Lite;
use Elite_Notification_Lite\Libs\Elite_Notification_Custom_Field;
use Elite_Notification_Lite\Libs\Elite_Notification_Item;
use Elite_Notification_Lite\Libs\Elite_Notification_Source_Base;
use Elite_Notification_Lite\Modules\Elite_Notification_Source;

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

/**
 * Class Ens_Woocommerce_Source
 *
 * @package Elite_Notification_Lite\Source
 */
class Ens_Woocommerce_Source extends Elite_Notification_Source_Base {
	/**
	 * Its property id
	 *
	 * @var string
	 */
	public $id = 'WOO-SALES';
	/**
	 * Its property source_name
	 *
	 * @var string
	 */
	public $source_name = 'WooCommerce';
	/**
	 * Its property is_activated_wc
	 *
	 * @var bool
	 */
	public $is_activated_wc = true;

	/**
	 * The on initialize is generated by appsbd
	 */
	public function on_initialize() {
		add_action(
			'save_post',
			function ( $post_d ) {
				Elite_Notification_Source::set_load_queue();
			},
			10
		);
		$this->is_show_title = false;
		if ( ! function_exists( 'WC' ) ) {
			$this->is_activated_wc = false;
		}
	}

	/**
	 * The get custom fields is generated by appsbd
	 *
	 * @return array|mixed
	 */
	public function get_custom_fields() {
		$cf = array(
			Elite_Notification_Custom_Field::get_textbox(
				'woo_des_template',
				$this->__( 'WooCommerce Description Template' ),
				'[customer] just purchased',
				'N',
				'Y',
				$this->__( 'ex. [customer] just purchased' ),
				'',
				'<span>' . $this->__( 'Use', 'your-text-domain' ) .
				' <strong>[customer]</strong> ' .
				$this->__( 'is for customer name', 'your-text-domain' ) . '</span>',
				'',
				'col-12 col-sm-12 col-md-6',
				'',
				'',
				''
			),
			Elite_Notification_Custom_Field::get_numeric(
				'woo_display_from_last',
				$this->__( 'Display From the Last' ),
				'',
				'N',
				'Y',
				$this->__( 'Display From the Last' ),
				'',
				'<span>' . $this->__( 'Last how many days will stay?', 'elite-notification' ) . '</span>',
				'',
				'col-6 col-sm-6 col-md-2',
				'',
				'',
				$this->__( 'Days' ),
			),
			Elite_Notification_Custom_Field::get_radio(
				'image_type',
				$this->__( 'Image Type' ),
				'P',
				'',
				array(
					array(
						'val'   => 'P',
						'title' => $this->__( 'Product Image' ),
					),
					array(
						'val'   => 'C',
						'title' => $this->__( 'Customer Image' ),
					),
				),
				'',
				'',
				'',
				'col-6 col-sm-6 col-md-4',
				''
			),
			Elite_Notification_Custom_Field::get_radio(
				'woo_status',
				$this->__( 'WooCommerce Status' ),
				'_A',
				'',
				array(
					array(
						'val'   => '_A',
						'title' => $this->__( 'All' ),
					),
					array(
						'val'   => 'wc-pending',
						'title' => $this->__( 'Pending payment' ),
					),
					array(
						'val'   => 'wc-processing',
						'title' => $this->__( 'Processing' ),
					),
					array(
						'val'   => 'wc-on-hold',
						'title' => $this->__( 'On hold' ),
					),
					array(
						'val'   => 'wc-completed',
						'title' => $this->__( 'Complete' ),
					),
					array(
						'val'   => 'wc-checkout-draft',
						'title' => $this->__( 'Draft' ),
					),
				),
				'',
				'',
				'',
				'col-12',
				''
			),
		);

		return $cf;
	}

	/**
	 * The get categories is generated by appsbd
	 *
	 * @return mixed|string[]
	 */
	public function get_categories() {
		return array( 'sales' );
	}

	/**
	 * The get items is generated by appsbd
	 *
	 * @param mixed $source_item It is source_item param.
	 *
	 * @return array|mixed
	 */
	public function get_items( $source_item ) {

		if ( ! $this->is_activated_wc ) {
			return array();
		}
		$des_template = $source_item->get_param_option( 'woo_des_template' );
		$woo_status   = $source_item->get_param_option( 'woo_status' );
		$image_type   = $source_item->get_param_option( 'image_type', 'P' );
		$days_ago     = $source_item->get_param_option( 'woo_display_from_last' );
		if ( function_exists( 'wc_get_orders' ) ) {
			$slnf_style = $source_item->slnf_style;
			$source_by  = $source_item->title;

			$woo_default_status = wc_get_order_statuses();
			$woo_statuses       = array();
			$skip_status        = array( 'wc-cancelled', 'wc-refunded', 'wc-failed' );
			foreach ( $woo_default_status as $key => $status ) {
				if ( ! in_array( $key, $skip_status ) ) {
					$woo_statuses[] = $key;
				}
			}

			$start_date = gmdate( 'Y-m-d H:i:s', strtotime( "-$days_ago days" ) );
			$end_date   = current_time( 'Y-m-d H:i:s' );
			$args       = array(
				'limit'        => $source_item->item_count,
				'date_created' => $start_date . '...' . $end_date,
			);
			if ( '_A' == $woo_status ) {
				if ( count( $woo_statuses ) > 0 ) {
					$args['status'] = $woo_statuses;
				}
			} else {
				$args['status'] = array( $woo_status );
			}

			$orders = wc_get_orders( $args );

			$response_array = array();

			foreach ( $orders as $order ) {
				$order_date = $order->get_date_created();

				$items            = $order->get_items();
				$order_item_count = is_countable( $items ) ? count( $items ) > 0 : 0;
				$selected_item    = null;

				foreach ( $items as $item ) {
					if ( ! $selected_item ) {
						$selected_item = $item;
					} else {
						$product_price = $this->get_product_price( $item->get_product() );
						if ( false != $product_price ) {
							$selected_item_price = $this->get_product_price( $selected_item->get_product() );
							if ( false !== $selected_item_price && $product_price > $selected_item_price ) {
								$selected_item = $item;
							}
						}
					}
				}

				$titlemsg        = $selected_item->get_name() . ' ' . ( $order_item_count > 1 ? $this->__(
					'& %s more products',
					$order_item_count
				) : '' );
				$item            = new Elite_Notification_Item();
				$item->id        = hash( 'crc32b', $order->get_id() );
				$item->source_id = $source_item->id;
				if ( 'U' == $image_type ) {
					$item->img = get_avatar_url( $order->get_user()->user_email, 32 );
				} else {
					$item->img = get_the_post_thumbnail_url( $selected_item->get_product()->get_id() );
				}

				$item->des          = '<div class=" apbd-el-first apbd-dtls-text">' . $this->get_template_msg(
					$des_template,
					$order
				) . '</div><div class="apbd-dtls-title" >' . ( $titlemsg ) . '</div>';
				$item->link_url     = $selected_item->get_product()->get_permalink();
				$item->view_style   = $slnf_style;
				$item->typ          = $this->__( 'Sales' );
				$item->nt_by        = '';
				$item->op_timestamp = $order_date->getOffsetTimestamp();
				$item->op_date      = gmdate(
					get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
					$item->op_timestamp
				);
				$response_array[]   = $item;
			}

			return $response_array;

		}

		return array();
	}

	/**
	 * The get product price is generated by appsbd
	 *
	 * @param mixed $product It is product param.
	 *
	 * @return false
	 */
	public function get_product_price( $product ) {
		if ( ! $this->is_activated_wc ) {
			return false;
		}
		if ( $product instanceof WC_Product ) {

			$product_price = $product->get_sale_price();
			if ( empty( $product_price ) ) {
				$product_price = $product->get_regular_price();
			}

			return $product_price;
		}

		return false;
	}

	/**
	 * The get template msg is generated by appsbd
	 *
	 * @param mixed $template It is template param.
	 * @param mixed $order It is order param.
	 *
	 * @return string|string[]
	 */
	public function get_template_msg( $template, $order ) {
		$customer = $order->get_user();

		if ( ! empty( $customer->first_name ) ) {
			$customer_name = $customer->first_name . ' ' . $customer->last_name;
		} else {
			$customer_name = $customer->display_name;
		}
		$customer_name = apbd_slnf_short_name( $customer_name );

		$data             = array();
		$data['customer'] = $customer_name;
		foreach ( array( 'customer' => 'customer' ) as $prop => $target ) {
			if ( isset( $data[ $prop ] ) ) {
				$template = str_replace( '[' . $target . ']', $data[ $prop ], $template );
			}
		}

		return $template;
	}

	/**
	 * The get icon is generated by appsbd
	 *
	 * @return mixed|string
	 */
	public function get_icon() {
		return $this->get_file_link( 'images/brand_images/source_woo.svg' );
	}

	/**
	 * The set from post data is generated by appsbd
	 *
	 * @param mixed $item_object It is item_object param.
	 *
	 * @return false|mixed
	 */
	public function set_from_post_data( &$item_object ) {
		$params = array(
			'woo_des_template'      => AppInput::post_value( 'woo_des_template' ),
			'woo_display_from_last' => AppInput::post_value( 'woo_display_from_last' ),
			'woo_status'            => AppInput::post_value( 'woo_status' ),
			'image_type'            => AppInput::post_value( 'image_type' ),
		);
		$is_ok  = true;
		if ( empty( $params['woo_des_template'] ) ) {
			Elite_Notification_Lite::add_error( 'WooCommerce Description template has been required' );
			$is_ok = false;
		}
		if ( empty( $params['woo_display_from_last'] ) ) {
			Elite_Notification_Lite::add_error( 'WooCommerce Display from last has been required' );
			$is_ok = false;
		}
		if ( empty( $params['woo_status'] ) ) {
			Elite_Notification_Lite::add_error( 'WooCommerce Status has been required' );
			$is_ok = false;
		}
		if ( empty( $params['image_type'] ) ) {
			Elite_Notification_Lite::add_error( 'Image Type has been required' );
			$is_ok = false;
		}
		if ( ! $is_ok ) {
			return false;
		}

		return $item_object->set_source_param( $params );
	}
}
