<?php

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

/**
 * Implements admin features of DateBook WooCommerce Subscription
 *
 * @class   DateBook_WC_Start
 * @package DateBook WooCommerce Subscription
 * @since   3.0
 */
if ( !class_exists( 'DateBook_WC_Start' ) ) {

    class DateBook_WC_Start {

		/**
         * Single instance of the class
         *
         */
        protected static $instance;

	    /**
	     * Post name of subscription
	     *
	     */
	    public $post_name = 'datebook_subscribe';

        /**
         * Returns single instance of the class
         *
         */
        public static function get_instance() {

            if ( is_null( self::$instance ) ) {
                self::$instance = new self();
            }
            return self::$instance;
        }

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

            /* general actions */
            add_filter( 'woocommerce_locate_core_template', array( $this, 'filter_woocommerce_template' ), 10, 3 );
            add_filter( 'woocommerce_locate_template', array( $this, 'filter_woocommerce_template' ), 10, 3 );

            /*Register custom post type DateBook_WC_Subscription */
	        DateBook_WC_Subscription_Post_Type();
            DateBook_WC_Subscription_Order();
            DateBook_WC_Subscription_Cart();
			
            // Change product prices
            add_filter('woocommerce_get_price_html', array($this, 'change_price_html'), 10, 2);

            add_filter( 'woocommerce_order_formatted_line_subtotal', array( $this, 'order_formatted_line_subtotal'), 10, 3 );

            // Ensure a subscription is never in the cart with products
            add_filter( 'woocommerce_add_to_cart_validation', array($this, 'cart_item_validate'), 10, 3 );
			
			add_filter('woocommerce_add_to_cart_redirect', array( $this, 'datebook_add_to_cart_redirect' ));
			
			add_filter( 'woocommerce_checkout_fields', array( $this, 'custom_override_checkout_fields' ));
			add_filter( 'woocommerce_billing_fields', array( $this, 'custom_override_billing_fields' ));
			add_filter( 'woocommerce_shipping_fields', array( $this, 'custom_override_shipping_fields' ));

			add_filter( 'woocommerce_email', array( $this, 'remove_billing_address_from_email' ));

        }


        /**
         * Redirect user directly to checkout page after he selects a plan
         *
         */
		public function datebook_add_to_cart_redirect( $fields ) {

			return wc_get_checkout_url();

		}


        /**
         * Remove Billing address fields from Checkout form
         *
         */
		public function custom_override_checkout_fields( $fields ) {

			$billing_fields = WC()->cart->needs_payment() ? of_get_option('woocommerce_billing_fields') : array();

			$billing_first_name = isset($billing_fields['billing_first_name']) && $billing_fields['billing_first_name'] == '1' ? 1 : 0;
			if ($billing_first_name == 0){
				unset($fields['billing']['billing_first_name']);
				unset($fields['shipping']['shipping_first_name']);
			}
			$billing_last_name = isset($billing_fields['billing_last_name']) && $billing_fields['billing_last_name'] == '1' ? 1 : 0;
			if ($billing_last_name == 0){
				unset($fields['billing']['billing_last_name']);
				unset($fields['shipping']['shipping_last_name']);
			}
			$billing_city = isset($billing_fields['billing_city']) && $billing_fields['billing_city'] == '1' ? 1 : 0;
			if ($billing_city == 0){
				unset($fields['billing']['billing_city']);
				unset($fields['shipping']['shipping_city']);
			}
			$billing_country = isset($billing_fields['billing_country']) && $billing_fields['billing_country'] == '1' ? 1 : 0;
			if ($billing_country == 0){
				unset($fields['billing']['billing_country']);
				unset($fields['shipping']['shipping_country']);
			}
			$billing_company = isset($billing_fields['billing_company']) && $billing_fields['billing_company'] == '1' ? 1 : 0;
			if ($billing_company == 0){
				unset($fields['billing']['billing_company']);
				unset($fields['shipping']['shipping_company']);
			}
			$billing_address = isset($billing_fields['billing_address']) && $billing_fields['billing_address'] == '1' ? 1 : 0;
			if ($billing_address == 0){
				unset($fields['billing']['billing_address_1']);
				unset($fields['shipping']['shipping_address_1']);
				unset($fields['billing']['billing_address_2']);
				unset($fields['shipping']['shipping_address_2']);
			}
			$billing_state = isset($billing_fields['billing_state']) && $billing_fields['billing_state'] == '1' ? 1 : 0;
			if ($billing_state == 0){
				unset($fields['billing']['billing_state']);
				unset($fields['shipping']['shipping_state']);
			}
			$billing_postcode = isset($billing_fields['billing_postcode']) && $billing_fields['billing_postcode'] == '1' ? 1 : 0;
			if ($billing_postcode == 0){
				unset($fields['billing']['billing_postcode']);
				unset($fields['shipping']['shipping_postcode']);
			}
			$enable_billing_email = isset($billing_fields['billing_email']) && $billing_fields['billing_email'] == '1' ? 1 : 0;
			if ($enable_billing_email == 0){
				//unset($fields['billing']['billing_email']);
				unset($fields['shipping']['shipping_email']);
			}
			$billing_phone = isset($billing_fields['billing_phone']) && $billing_fields['billing_phone'] == '1' ? 1 : 0;
			if ($billing_phone == 0){
				unset($fields['billing']['billing_phone']);
				unset($fields['shipping']['shipping_phone']);
			}

			return $fields;
		}

		public function custom_override_billing_fields( $fields ) {

			$billing_fields = WC()->cart->needs_payment() ? of_get_option('woocommerce_billing_fields') : array();

			$billing_country = isset($billing_fields['billing_country']) && $billing_fields['billing_country'] == '1' ? 1 : 0;
			if ($billing_country == 0){
				unset($fields['billing_country']);
			}
			$billing_company = isset($billing_fields['billing_company']) && $billing_fields['billing_company'] == '1' ? 1 : 0;
			if ($billing_company == 0){
				unset($fields['billing']['billing_company']);
			}
			$billing_address = isset($billing_fields['billing_address']) && $billing_fields['billing_address'] == '1' ? 1 : 0;
			if ($billing_address == 0){
				unset($fields['billing']['billing_address_1']);
				unset($fields['billing']['billing_address_2']);
			}
			$billing_state = isset($billing_fields['billing_state']) && $billing_fields['billing_state'] == '1' ? 1 : 0;
			if ($billing_state == 0){
				unset($fields['billing']['billing_state']);
			}
			$billing_postcode = isset($billing_fields['billing_postcode']) && $billing_fields['billing_postcode'] == '1' ? 1 : 0;
			if ($billing_postcode == 0){
				unset($fields['billing']['billing_postcode']);
			}
			$billing_email = isset($billing_fields['billing_email']) && $billing_fields['billing_email'] == '1' ? 1 : 0;
			if ($billing_email == 0){
				//unset($fields['billing']['billing_email']);
			}

			return $fields;
		}

		public function custom_override_shipping_fields( $fields ) {
			unset($fields['shipping_country']);
			unset($fields['shipping']['shipping_company']);
			unset($fields['shipping']['shipping_address_1']);
			unset($fields['shipping']['shipping_address_2']);
			unset($fields['shipping']['shipping_state']);
			unset($fields['shipping']['shipping_postcode']);
			unset($fields['shipping']['shipping_email']);

			return $fields;
		}


        /**
         * Remove Billing address fields from Email
         *
         */
		public function remove_billing_address_from_email( $email_class ) {

			remove_action( 'woocommerce_email_customer_details', array( $email_class, 'email_addresses' ), 20, 3 );

		}


        /**
         * Locate default templates of woocommerce in plugin, if exists
         *
         */
        public function filter_woocommerce_template( $core_file, $template, $template_base ) {

            $located = datebook_wcaddon_locate_template( $template );

            if ( $located ) {
                return $located;
            }
            else {
                return $core_file;
            }
        }


	    public function change_price_html( $price, $product ) {

	        if ( ! $this->is_subscription( $product->get_id() ) ) {
		        return $price;
	        }

	        $price_is_per      = datebook_get_prop( $product, '_wcaddon_price_is_per' );
	        $price_time_option = datebook_get_prop( $product, '_wcaddon_price_time_option' );
	        $price_time_option_string = datebook_wc_get_price_per_string( $price_is_per, $price_time_option );

	        $price .= ' / ' . $price_time_option_string;

            return $price;

        }

	    public function is_subscription( $product ) {
			
			if(!empty($product)){

			    if ( is_numeric( $product ) ) {
				    $product = wc_get_product( $product );
			    }

			    $is_subscription = datebook_get_prop( $product, '_datebook_subscribe' );
			    $price_is_per    = datebook_get_prop( $product, '_wcaddon_price_is_per' );
			
				if(!empty($product->get_id())){
					$function_product_get_id = $product->get_id();
				} else {
					$function_product_get_id =  '';
				}

				return apply_filters( 'wcaddon_is_subscription', ( $is_subscription == 'yes' && $price_is_per != '' ) ? true : false, $function_product_get_id );
			}

        }

        /**
         * Check if in the cart there are subscription that needs shipping
         *
         */
	    public function cart_has_subscription_with_shipping() {

		    $cart_has_subscription_with_shipping = false;

		    $cart_contents = WC()->cart->get_cart();

		    if ( ! isset( $cart_contents ) || empty( $cart_contents ) ) {
			    return $cart_has_subscription_with_shipping;
		    }

		    foreach ( $cart_contents as $cart_item ) {
			    $product = $cart_item['data'];
			    if ( $this->is_subscription( $product->id ) && $product->needs_shipping() ) {
				    $cart_has_subscription_with_shipping = true;
			    }
		    }

		    return apply_filters( 'wcaddon_cart_has_subscription_with_shipping', $cart_has_subscription_with_shipping );

	    }

	    public function cart_item_validate( $valid, $product_id, $quantity ) {
		    if ( $this->is_subscription( $product_id ) && $item_key = $this->cart_has_subscriptions() ) {
			    $this->clean_cart_from_subscriptions( $item_key );
			    $message = esc_html__( 'A subscription has been removed from your cart. You cannot purchase different subscriptions at the same time.', 'datebook' );
			    wc_add_notice( $message, 'notice' );
		    }

		    return $valid;
	    }

        /**
         * Removes all subscription products from the shopping cart.
         *
         */
        public function clean_cart_from_subscriptions( $item_key ) {
            WC()->cart->set_quantity( $item_key, 0 );
        }

        /**
         * Check if in the cart there are subscription
         *
         */
	    public function cart_has_subscriptions() {
		    $contents = WC()->cart->cart_contents;
		    if ( ! empty( $contents ) ) {
			    foreach ( $contents as $item_key => $item ) {
				    if ( $this->is_subscription( $item['product_id'] ) ) {
					    return $item_key;
				    }
			    }
		    }

		    return false;
	    }

	    public function order_formatted_line_subtotal( $subtotal, $item, $order ) {

		    $product_id = $item['product_id'];
		    $product    = wc_get_product( $product_id );

		    if ( ! $this->is_subscription( $product ) ) {
			    return $subtotal;
		    }

		    $price_is_per      = datebook_get_prop( $product, '_wcaddon_price_is_per' );
		    $price_time_option = datebook_get_prop( $product, '_wcaddon_price_time_option' );

		    $subtotal .= ' / ' . $price_is_per . ' ' . $price_time_option;

		    return apply_filters( 'wcaddon_order_formatted_line_subtotal', $subtotal, $item, $this, $product );

	    }

        /**
         * Check if in the order there are subscription
         *
         */
	    public function order_has_subscription( $order_id ) {

		    $order       = wc_get_order( $order_id );
		    $order_items = $order->get_items();

		    if ( empty( $order_items ) ) {
			    return false;
		    }

		    foreach ( $order_items as $key => $order_item ) {
			    $id = ( $order_item['variation_id'] ) ? $order_item['variation_id'] : $order_item['product_id'];

			    if ( DateBook_WC_Start()->is_subscription( $id ) ) {
				    return true;
			    }
		    }

		    return false;
	    }
    }


}

/**
 * Unique access to instance of DateBook_WC_Start class
 *
 */
function DateBook_WC_Start() {
    return DateBook_WC_Start::get_instance();
}