<?php
/**
 * Woostify Pre-Order Manager
 *
 * @package  Woostify Pro
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'Woostify_Pre_Order_Manager' ) ) {

	/**
	 * Class Woostify Pre-Order Manager
	 */
	class Woostify_Pre_Order_Manager {
		/**
		 * Instance Variable
		 *
		 * @var instance
		 */
		private static $instance;

		/**
		 *  Initiator
		 */
		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Constructor.
		 */
		public function __construct() {

			add_action( 'init', array( $this, 'register_preorder_order_status') );
			add_filter( 'wc_order_statuses', array( $this, 'custom_order_status_single_order_dropdown') );
            add_action( 'woocommerce_checkout_update_order_meta',array( $this, 'manage_pre_orders' ), 10,  2 );

		}

		/*
		* Register new order status
		*/
		public function register_preorder_order_status() {
			register_post_status( 'wc-woostify-preorder', array(
				'label'                     => 'On Pre Ordered',
				'public'                    => true,
				'exclude_from_search'       => false,
				'show_in_admin_all_list'    => true,
				'show_in_admin_status_list' => true,
				'label_count'               => _n_noop( 'On Pre Ordered <span class="count">(%s)</span>', 'On Pre Ordered <span class="count">(%s)</span>' )
			) );
		}

		/*
		* Add to list of WC order statuses
		*/
		public function custom_order_status_single_order_dropdown( $order_statuses ) {
			$order_statuses['wc-woostify-preorder'] = 'On Pre Ordered';
			return $order_statuses;
		}

		public function check_pre_order_products( $items ) {
			if ( isset( $items['line_items'] ) ) {
				$items = $items['line_items'];
			}

			$preOrderProducts = @array_filter( $items, function ( $v ) {
				return 'onpreorder' === get_post_meta( $v['product_id'], '_stock_status', true ) && 
				new \DateTime( get_post_meta( $v['product_id'], '_onpreorder_date_to', true ) ) > new \DateTime() || 
				'onpreorder' === get_post_meta( $v['variation_id'], '_stock_status', true ) && 
				new \DateTime( get_post_meta( $v['variation_id'], '_onpreorder_date_to', true ) ) > new \DateTime();
			} );

			return $preOrderProducts;
		}

        public function manage_pre_orders( $orderId, $data ) {
            $order = wc_get_order( $orderId );

			global $woocommerce;
			$cart = $woocommerce->cart->get_cart();
			$preOrderProducts = $this->check_pre_order_products( $cart );
			if( !empty($preOrderProducts) && count($preOrderProducts) > 0 ){
				$order->set_status( 'wc-woostify-preorder' );
			}

            $order->save();
    
        }


	}

	Woostify_Pre_Order_Manager::get_instance();

}



