<?php
/**
 * @version    1.0.1
 * @package    Sparta
 * @author     Your Team <support@univertheme.com>
 * @copyright  Copyright (C) 2014 yourdomain.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 */

class Sparta_Woocommerce {
	/**
	 * Variable to hold the initialization state.
	 *
	 * @var  boolean
	 */
	protected static $initialized = false;

	/**
	 * Initialize functions.
	 *
	 * @return  void
	 */
	public static function initialize() {
		// Do nothing if start functions already initialized.
		if ( self::$initialized ) {
			return;
		}
          

		add_action( 'after_setup_theme', array( __CLASS__, 'sparta_woo_setup' ) );
        add_action( 'woocommerce_before_shop_loop_item',  array( __CLASS__, 'sparta_wrap_product_item' ) , 0 );
        add_action( 'woocommerce_after_shop_loop_item',   array( __CLASS__, 'sparta_wrap_product_item_close' ) , 40 );
        add_action('woocommerce_single_product_summary', array(__CLASS__, 'sparta_template_single_availability'), 11);
        add_filter('loop_shop_columns', array( __CLASS__, 'sparta_loop_columns' ) );
        remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20 );
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
        add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_link_close', 12 );
        remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
        add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_link_open', 1 );
        remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
        remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
        add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 9 );
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );


        remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
        add_action( 'woocommerce_before_shop_loop_item_title', array( __CLASS__,  'sparta_woocommerce_template_loop_product_thumbnail'), 10 );

        add_action( 'init', array( __CLASS__,  'custom_add_to_cart_quantity_handler') );
        
        $woo_detail_layout = get_theme_mod('sparta_woo_detail_layout','no-sidebar');

        if ( $woo_detail_layout === 'right-sidebar' || $woo_detail_layout === 'left-sidebar' ) {
            add_filter( 'woocommerce_output_related_products_args', array( __CLASS__,  'sparta_related_products_args') );
            add_filter( 'woocommerce_upsell_display_args', array( __CLASS__,  'sparta_wc_change_number_related_products'), 20 );
        }

        /**
         * Cart fragment
         *
         * @see sparta_cart_link_fragment()
         */
        if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '2.3', '>=' ) ) {
            add_filter( 'woocommerce_add_to_cart_fragments', array( __CLASS__,  'sparta_cart_link_fragment') );
        } else {
            add_filter( 'add_to_cart_fragments', array( __CLASS__,  'sparta_cart_link_fragment') );
        }

        add_action( 'sparta_shop_loop_action', array( __CLASS__, 'sparta_loop_action_open' ), 10 );
        add_action('sparta_shop_loop_action','woocommerce_template_loop_add_to_cart', 12 );
        add_action( 'sparta_shop_loop_action', array( __CLASS__, 'sparta_loop_action_close' ), 15 );

        // State that initialization completed.
		self::$initialized = true;

	}

    public static function sparta_woocommerce_template_loop_product_thumbnail() {
        echo woocommerce_get_product_thumbnail('sparta-thumb-square'); // WPCS: XSS ok.
    }


    public static function sparta_loop_action_open(){
        echo '<div class="loop-action">';
    }

    public static function sparta_loop_action_close(){
        echo '</div>';
    }


    public static function sparta_header_cart_mobile() {
        if ( class_exists( 'WooCommerce' )  ) {
          
        ?>
        <div class="site-header-cart">
                <a class="cart-contents" href="<?php echo esc_url( wc_get_cart_url() ); ?>" title="<?php esc_attr_e( 'View your shopping cart', 'sparta' ); ?>">
                <?php echo wp_kses_post( WC()->cart->get_cart_subtotal() ); ?> <span class="count"><?php echo wp_kses_data( sprintf( _n( '%d', '%d', WC()->cart->get_cart_contents_count(), 'sparta' ), WC()->cart->get_cart_contents_count() ) );?></span>
            </a>
        </div>           
        
        <?php
        }
    }

    /**
     * Cart Fragments
     * Ensure cart contents update when products are added to the cart via AJAX
     *
     * @param  array $fragments Fragments to refresh via AJAX.
     * @return array            Fragments to refresh via AJAX
     */

    public static function sparta_cart_link_fragment( $fragments ) {
        global $woocommerce;

        ob_start();
        ?>
            <a class="cart-contents" href="<?php echo esc_url( wc_get_cart_url() ); ?>" title="<?php esc_attr_e( 'View your shopping cart', 'sparta' ); ?>">
                <?php echo wp_kses_post( WC()->cart->get_cart_subtotal() ); ?> <span class="count"><?php echo wp_kses_data( sprintf( _n( '%d', '%d', WC()->cart->get_cart_contents_count(), 'sparta' ), WC()->cart->get_cart_contents_count() ) );?></span>
            </a>
        <?php
        $fragments['a.cart-contents'] = ob_get_clean();

        ob_start();
        ?>
            <a class="footer-cart-contents" href="<?php echo esc_url( wc_get_cart_url() ); ?>" title="<?php esc_attr_e( 'View your shopping cart', 'sparta' ); ?>">
                <span class="count"><?php echo wp_kses_data( sprintf( _n( '%d', '%d', WC()->cart->get_cart_contents_count(), 'sparta' ), WC()->cart->get_cart_contents_count() ) );?></span>
            </a>
        <?php
        $fragments['a.footer-cart-contents'] = ob_get_clean();

        return $fragments;
    }    
    

    /**
     * Change number of related products output
     */ 
    public static function sparta_related_products_args( $args ) {
        $args['posts_per_page'] = 3; // 3 related products
        $args['columns'] = 3; // arranged in 3 columns
        return $args;
    }

    public static function sparta_wc_change_number_related_products( $args ) {

        $args['posts_per_page'] = 3;
        $args['columns'] = 3; //change number of upsells here
        return $args;
    }

    /**
     * Add requires JavaScript.
     */
    public static function custom_add_to_cart_quantity_handler() {
        if ( class_exists('WooCommerce') ) :
            wc_enqueue_js( '
                jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
                    return false;
                });
                jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
                    var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
                    // For AJAX add-to-cart actions
                    add_to_cart_button.data( "quantity", jQuery( this ).val() );
                    // For non-AJAX add-to-cart actions
                    add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
                });
            ' );
        endif;
    }    

    public static function sparta_woo_sorting_wrapper() {
            echo '<div class="sparta-woo-sorting">';
    }
    
    public static function sparta_woo_sorting_wrapper_close() {
            echo '</div>';
    }
    
    public static function sparta_woo_setup() {
        // Declare WooCommerce support
        add_theme_support( 'woocommerce' );
        add_theme_support( 'wc-product-gallery-zoom' );
        add_theme_support( 'wc-product-gallery-lightbox' );
        add_theme_support( 'wc-product-gallery-slider' );
    }

    public static function sparta_template_single_availability(){
        global $product;

        $product_stock = self::sparta_product_get_availability();
        $availability_text = empty($product_stock['availability'])?esc_html__('Available In Stock', 'sparta'):esc_attr($product_stock['availability']);
        ?>
        <div class="vk-status <?php echo esc_attr($product_stock['class']); ?>" data-original="<?php echo esc_attr($availability_text) ?>" data-class="<?php echo esc_attr($product_stock['class']) ?>">
            <?php echo esc_html__('AVAILBLE:','sparta'); ?> <span class="avail-txt"><?php echo esc_html($availability_text); ?></span>
        </div>
        <?php
    }

    public static function sparta_product_get_availability(){
        global $product;
        $availability = $class = '';
        if ( ! $product->is_in_stock() ) {
            $availability = esc_html__( 'Out of stock', 'sparta' );
        } elseif ( $product->managing_stock() && $product->is_on_backorder( 1 ) ) {
            $availability = esc_html__( 'Available on backorder', 'sparta' );
        } elseif ( $product->managing_stock() ) {
            $availability = wc_format_stock_for_display( $product );
        } else {
            $availability = '';
        }
        
        if ( ! $product->is_in_stock() ) {
            $class = 'out-of-stock';
        } elseif ( $product->managing_stock() && $product->is_on_backorder( 1 ) ) {
            $class = 'available-on-backorder';
        } else {
            $class = 'in-stock';
        }

        return array( 'availability' => $availability, 'class' => $class );
    }


    public static function sparta_loop_columns() {
       $column = get_theme_mod('sparta_woo_archive_grid_columns','three-columns' );
       if($column == 'two-columns'){
           return 2;
       }elseif($column == 'four-columns'){
           return 4;
       }elseif($column == 'three-columns'){
           return 3;
       }
       else{
           return 4;
       }
       
     }


    public static function sparta_shop_classes(){
        $classes = array();

        if ((is_shop() || is_product_category() || is_product_tag()) ) {
            $classes['shop_columns'] = get_theme_mod('sparta_woo_archive_grid_columns','three-columns' );
        }

        echo implode(' ', $classes);
    }
    public static function sparta_wrap_product_item() {
        ?><div class="vk-shop-item"><?php
    }
    public static function sparta_wrap_product_item_close() {
        ?></div><?php
    }
	
}