<?php

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}
global $di_data;
require_once DI_DIR . '/includes/single-product-func.php';
//require_once DI_DIR . '/includes/order-tracking.php';
require_once DI_DIR . '/includes/my-account-func.php';
require_once DI_DIR . '/includes/prod-hover-btns.php';

//Change number or products per row
add_filter('loop_shop_columns', 'dina_loop_columns', 999);
if (!function_exists('dina_loop_columns')) {
    function dina_loop_columns() {
        global $di_data;
        $prods = $di_data['product_col'];
        return $prods;
    }
}

//Change number of products that are displayed per page (shop page)
add_filter( 'loop_shop_per_page', 'dina_product_per_page', 20 );
function dina_product_per_page( $cols ) {
    global $di_data;
    $cols = $di_data['product_num'];
    return $cols;
}

//Check product is free
function dina_woo_free( $id ){
$product = wc_get_product( $id );
if ( '' === $product->get_price() || 0 == $product->get_price() && defined( 'SOMDN_PATH' )) {
    return true;
} else {
    return false;
}
}

//Free Price for free products
add_filter( 'woocommerce_get_price_html', 'dina_free_zero_empty', 100, 2 );
function dina_free_zero_empty( $price, $product ){
    global $di_data;

    $coming = get_post_meta( $product->get_id(), 'dina_coming', true );

    $variable_call = false;
    if($product->is_type( 'variable' )) {
        $min_var_reg_price = $product->get_variation_regular_price( 'min', true );
        $min_var_sale_price = $product->get_variation_sale_price( 'min', true );
        $max_var_reg_price = $product->get_variation_regular_price( 'max', true );
        $max_var_sale_price = $product->get_variation_sale_price( 'max', true );
        if ( ( $min_var_reg_price == $max_var_reg_price && $max_var_reg_price == 0 ) || ( $min_var_sale_price == $max_var_sale_price && $max_var_sale_price == 0 ) || ( $min_var_reg_price === $max_var_reg_price && $max_var_reg_price === '' ) || ( $min_var_sale_price === $max_var_sale_price && $max_var_sale_price === '' ) ) {
            $variable_call = true;
        }
    }

    if ( show_login_price() ) {

        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);

        if( is_singular('product') ) {
            if (function_exists('digits_version') && $di_data['digits_mode']) {
                $digits_mode = ( $di_data['digits_page'] ? 'digitsbtn digitlink' : 'digitsbtn digitpopup' );
                $price = '<span class="woocommerce-Price-amount amount '. $digits_mode .'">'.__('Login to see prices','dina-kala').'</span>';
            } elseif( $di_data['merge_user_btn'] ) {
                $login_link = ( $di_data['ch_login_link'] ? 'href="'. $di_data['login_link'] .'"' : 'href="'. esc_url(home_url()) .'/my-account"' );
                $price = '<a title="'. __('Login Or Register', 'dina-kala') .'" class="login-price-link" '. $login_link .'>';
                $price .= '<span class="woocommerce-Price-amount amount">'.__('Login to see prices','dina-kala').'</span>';
                $price .= '</a>';
            } else {
                $login_link = ( $di_data['ch_login_link'] ? 'href="'. $di_data['login_link'] .'"' : 'href="javascript:void(0)" onclick="openLogin()"' );
                $price = '<a title="'. __('Login Or Register', 'dina-kala') .'" class="login-price-link" '. $login_link .'>';
                $price .= '<span class="woocommerce-Price-amount amount">'.__('Login to see prices','dina-kala').'</span>';
                $price .= '</a>';
            }
        } else {
            $price = '<span class="woocommerce-Price-amount amount">'.__('Login to see prices','dina-kala').'</span>';
        }

    } elseif ( $coming ) {

        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
        $price = '<span class="woocommerce-Price-amount amount">'.__('Coming Soon...','dina-kala').'</span>';

    } elseif ( ( $product->is_type( 'variable' ) && $variable_call === true ) && $di_data['show_zero_call'] && ('' === $product->get_price() || 0 == $product->get_price()) ) {
        
        $price = '<span class="woocommerce-Price-amount amount">'.__('Call!','dina-kala').'</span>';

        if(is_singular('product') && !empty($di_data['zero_call_link'])) {
            $price = '<a class="call-pro-link" href="'. $di_data['zero_call_link'] .'" title="'.__('Call!','dina-kala').'" target="_blank">' . $price;
            $price = $price .'</a>';
        }
        
    } elseif ( !$product->is_type( 'variable' ) && $di_data['show_zero_call'] && ('' === $product->get_price() || 0 == $product->get_price()) ) {

        $price = '<span class="woocommerce-Price-amount amount">'.__('Call!','dina-kala').'</span>';

        if(is_singular('product') && !empty($di_data['zero_call_link'])) {
            $price = '<a class="call-pro-link" href="'. $di_data['zero_call_link'] .'" title="'.__('Call!','dina-kala').'" target="_blank">' . $price;
            $price = $price .'</a>';
        }

    } elseif ( ( $product->is_type( 'variable' ) && $variable_call === true ) && $di_data['show_free_price'] && ('' === $product->get_price() || 0 == $product->get_price()) ) {

        $price = '<span class="woocommerce-Price-amount amount">'.__('Free!','dina-kala').'</span>';
    }
    return $price;
}

//Change several of the breadcrumb defaults
add_filter( 'woocommerce_breadcrumb_defaults', 'dina_woocommerce_breadcrumbs' );
function dina_woocommerce_breadcrumbs() {
    global $di_data;
    if($di_data['change_home_text']) {
        $home_text = $di_data['home_text'];
    } else {
        $home_text = _x( 'Home', 'breadcrumb', 'dina-kala' );
    }
    $bread_mobile = ($di_data['show_bread_mobile'] ? '' : ' mobile-hidden' );
    return array(
            'delimiter'   => ' &#47; ',
            'wrap_before' => '<div class="row bread-row'.$bread_mobile.'"><nav class="col-12 shadow-box breadcrumbs" itemprop="breadcrumb">',
            'wrap_after'  => '</nav></div>',
            'before'      => '',
            'after'       => '',
            'home'        => $home_text,
        );
}

//Show cart contents / total Ajax
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
	global $woocommerce;
	ob_start();
	?>
	<i class="cart-amount">
    <?php echo $woocommerce->cart->cart_contents_count; ?></i>
	<?php
	$fragments['.cart-amount'] = ob_get_clean();
	return $fragments;
}

//Total Sales of woocommerce products
function di_woo_get_total_sales() {
    $total_orders = count(wc_get_orders( array(
        'status' => 'completed',
        'return' => 'ids',
        'limit' => -1,
    )));
    return $total_orders;
}

//Woo Dis price
function disw_price ($id){
    $product = wc_get_product( $id );
    if($product->is_type( 'variable' )){
        $r_price = $product->get_variation_regular_price( 'min' );
        $s_price = $product->get_variation_sale_price( 'min' );
        if($r_price == $s_price) {
            $r_price = $product->get_variation_regular_price( 'max' );
            $s_price = $product->get_variation_sale_price( 'max' );
        }
    } else {
        $r_price = $product->get_regular_price();
        $s_price = $product->get_sale_price();
    }
    $d_price = (int)$r_price - (int)$s_price;
    $t_price = round(($d_price/$r_price)*100);
    return $t_price;
}

//Dina Dis price
function dina_dis_price ($id){
    global $di_data;
    $product = wc_get_product( $id );
    if($product->is_type( 'variable' )){
        $s_price = $product->get_variation_sale_price( 'min' );
    } else {
        $s_price = $product->get_sale_price();
    }
    if(!empty($s_price) && disw_price ($id) != 0) {
        if($di_data['display_spec']) {
            $t_price ='<span class="product-dis product-dis-spec">'. __( 'Sale!', 'dina-kala' ) .'</span>';
        } elseif(is_rtl()) {
            $t_price ='<span class="product-dis">٪'. disw_price ($id) .'</span>';
        } else {
            $t_price ='<span class="product-dis">'. disw_price ($id) .'%</span>';
        }
        return $t_price;
    }
}

//dina_woo_show_page_title
add_filter( 'woocommerce_show_page_title', 'dina_woo_show_page_title' );
function dina_woo_show_page_title() {
    return false;
}

//dina_woo_add_product_class
add_filter('post_class', 'dina_woo_add_product_class');
function dina_woo_add_product_class($classes) {
    global $di_data;
    global $product;
    if(is_single() && 'product' == get_post_type()) {
        $pside = get_post_meta( get_the_ID(), 'dina_pside', true );
        $content_sticky = ($di_data['side_sticky'] ? 'content-sticky' : '');
        $classes[] .= $content_sticky;
        if($pside == 'wside') { 
        $classes[] .= 'col-12';
        }
        elseif( !empty($pside) ) {
            $classes[] .= 'col-lg-9 col-12';
        } elseif ($di_data['product_side'] > 0) {
        $classes[] .= 'col-lg-9 col-12';}
        else{
            $classes[] .= 'col-12';
        }
        $classes[] .= ( !$product->is_type( 'variable' ) && $di_data['show_zero_call'] && ( '' === $product->get_price() || 0 == $product->get_price() ) ? 'call-pro' : '' );
        $classes[] .= ( $di_data['prod_tab_style'] == 'sttwo'  ? 'product-tab-style-two' : '' );
        $classes[] .= ( is_rtl()  ? 'product-rtl' : 'product-ltr' );
        $classes[] .= ( $di_data['product_page_style'] == 'stone'  ? 'product-page-style-one' : 'product-page-style-two' );
        $classes[] .= ( get_post_meta( $product->get_id(), 'dina_coming', true )  ? 'product-coming' : '' );
        $classes[] .= ( show_login_price() ? 'dina-login-price' : '' );
    }
    return $classes;
}

//dina_woo_before_main_content
add_action('woocommerce_before_main_content', 'dina_woo_before_main_content',21);
function dina_woo_before_main_content() {
    global $di_data;

    if ( $di_data['show_sub_cats'] && is_product_category() ) {
        dina_show_sub_cats();
    }

    if ( $di_data['show_head_banner'] && !is_checkout() && !is_cart() ) {
         dina_header_banner(); 
        } 

    if( !is_singular('product') ) {
        $side = ($di_data['product_archive_side'] == 2 ? ' right-side' : ''); ?> 
        <div class="row prod-row<?php echo $side ?>">
    <?php } else {

    $pside = get_post_meta( get_the_ID(), 'dina_pside', true );

    if($pside == 'rside') { 
        $side = ' right-side';
    } elseif ($pside == 'lside') {
        $side = '';
    } elseif ( $di_data['product_side'] == 2 ) {
        $side = ' right-side';
    } else {
        $side = '';
    } ?>

    <div class="row prod-row<?php echo $side ?>">
    <?php }
}

//dina_woo_after_main_content
add_action('woocommerce_after_main_content', 'dina_woo_after_main_content');
function dina_woo_after_main_content() { ?>
    </div>    
<?php }

//dina_woo_before_shop_loop
add_action('woocommerce_before_shop_loop', 'dina_woo_before_shop_loop',17);
function dina_woo_before_shop_loop() { 
global $di_data;
$content_sticky = ($di_data['side_sticky'] ? ' content-sticky' : '');
$ajax_prod = ($di_data['ajax_prod'] ? ' ajax-prod' : '');
$col = ($di_data['product_archive_side'] == 0 ? 'col-12' : 'col-lg-9 col-12'); ?>
<div class="<?php echo $col; ?><?php echo $content_sticky; ?><?php echo $ajax_prod; ?>">
<?php }

//dina_woo_before_order_con
add_action('woocommerce_before_shop_loop', 'dina_woo_before_order_con',19);
function dina_woo_before_order_con() { 
    global $di_data;

    $show_filter = (dina_check_side() == 2 && $di_data['show_filter'] ? ' show-filter' : ''); ?>

    <div class="col-12 shadow-box woocommerce-ordering-con<?php echo $show_filter; ?>">

    <i class="fal fa-sort-amount-up-alt sort-icon" aria-hidden="true"></i>

    <ul class="dina-order-products">
    <?php
    
    if( isset($_GET['orderby']) ) {
        $orderby = $_GET['orderby'];
    } elseif( is_search() ) {
        $orderby = 'relevance';
    } else {
        $orderby = get_option( 'woocommerce_default_catalog_orderby' );
    }
    ?>

        <?php if( is_search() ){ ?>
        <li class="order-item order-relevance<?php echo ($orderby == 'relevance' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'relevance' ); ?>">
                <?php _e('Relevance' , 'dina-kala'); ?>
            </a>
        </li>

        <?php } elseif( $orderby == 'menu_order' || $orderby == '' ){ ?>
        <li class="order-item order-menu-order<?php echo ($orderby == 'menu_order' || $orderby == '' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'menu_order' ); ?>">
                <?php _e('Default' , 'dina-kala'); ?>
            </a>
        </li>
        <?php } ?>

        <li class="order-item order-rating<?php echo ($orderby == 'rating' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'rating' ); ?>">
                <?php _e('Rating' , 'dina-kala'); ?>
            </a>
        </li>

        <li class="order-item order-popularity<?php echo ($orderby == 'popularity' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'popularity' ); ?>">
                <?php _e('Popularity' , 'dina-kala'); ?>
            </a>
        </li>

        <li class="order-item order-date<?php echo ($orderby == 'date' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'date' ); ?>">
                <?php _e('Latest' , 'dina-kala'); ?>
            </a>
        </li>

        <li class="order-item order-price<?php echo ($orderby == 'price' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'price' ); ?>">
                <?php _e('Low Price' , 'dina-kala'); ?>
            </a>
        </li>

        <li class="order-item order-price-desc<?php echo ($orderby == 'price-desc' ? ' is-active' : ''); ?>">
            <a rel="nofollow" href="<?php echo dina_order_get_link( 'price-desc' ); ?>">
                <?php _e('High Price' , 'dina-kala'); ?>
            </a>
        </li>
    </ul>
<?php }

//dina_order_get_link
function dina_order_get_link( $order_type ) {
    $base_link            = dina_shop_page_link( true );
    $link                 = remove_query_arg( 'orderby', $base_link );

    if( $order_type != 'menu_order' ) {
        $link = add_query_arg( 'orderby', $order_type, $link );
        $link = str_replace( '%2C', ',', $link );
    }

    return $link;
 }

//dina_woo_after_order
add_action('woocommerce_before_shop_loop', 'dina_woo_after_order',35);
function dina_woo_after_order(){ 
global $di_data;
if ( dina_check_side() == 2 && $di_data['show_filter'] ) { ?>
    <span class="show-filter-btn open-side" onclick="openSide()">
        <span aria-hidden="true" class="fal fa-filter" title="<?php _e('Show filters', 'dina-kala'); ?>"></span>
        <span><?php _e('Show filters', 'dina-kala'); ?></span>
    </span>
<?php } ?>
</div>
<?php }

//Remove query var from URL
function removeqsvar($url, $varname) {
    return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}

//Show Product Category Description
remove_action( 'woocommerce_archive_description', 'woocommerce_taxonomy_archive_description' );
remove_action( 'woocommerce_archive_description', 'woocommerce_product_archive_description' );
if($di_data['show_on_top_cat']){
add_action('woocommerce_before_shop_loop', 'dina_product_archive_description', 18);
} else {
add_action('woocommerce_after_shop_loop', 'dina_product_archive_description',14);
}

function dina_product_archive_description() {
    global $di_data;
    if ( is_search() || is_shop() ) { 
        return;
    } 
    $cat_full = (!$di_data['show_full_text_cat'] ? ' class="cat-text dina-more-less" data-more="'.__('Show More','dina-kala').'" data-less="'.__('Show Less','dina-kala').'"' : '');
    the_archive_description('<div class="shadow-box cat-desc col-12">
    <div'.$cat_full.'>','</div>
    </div>');
}

//dina_woo_after_shop_loop
add_action('woocommerce_after_shop_loop', 'dina_woo_after_shop_loop',15);
function dina_woo_after_shop_loop() { ?>
    </div>    
<?php }

//remove woocommerce_breadcrumb
if(!$di_data['show_bread']) {
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
}

//dina_pagination_args
add_filter( 'woocommerce_pagination_args', 'dina_pagination_args' );
function dina_pagination_args() {
    $total   = isset( $total ) ? $total : wc_get_loop_prop( 'total_pages' );
    $current = isset( $current ) ? $current : wc_get_loop_prop( 'current_page' );
    $base    = isset( $base ) ? $base : esc_url_raw( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) );
    $format  = isset( $format ) ? $format : '';
    if ( $total <= 1 ) {
        return;
    }
        return array(
            'base'         => $base,
            'format'       => $format,
            'add_args'     => false,
            'current'      => max( 1, $current ),
            'total'        => $total,
            'prev_text' => __('<i class="fal fa-chevron-right" aria-hidden="true" title="Next"></i>') ,
            'next_text' => __('<i class="fal fa-chevron-left" aria-hidden="true" title="Prev"></i>') ,
            'type'         => 'list',
            'end_size'     => 3,
            'mid_size'     => 3,
            );
}

//dina_cart_item_name
add_filter( 'woocommerce_cart_item_name', 'dina_cart_item_name', 10, 3 );
function dina_cart_item_name( $item_name,  $cart_item,  $cart_item_key ) {
    return '<span class="side-cart-name">'.$item_name.'</span>';
}

//dina_no_products_found
remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );
add_action('woocommerce_no_products_found', 'dina_no_products_found', 10);
function dina_no_products_found(){
    global $di_data;
    $content_sticky = ($di_data['side_sticky'] ? ' content-sticky' : '');
    $col = ($di_data['product_archive_side'] == 0 ? 'col-12' : 'col-lg-9 col-12');
    ?>
    <div class="<?php echo $col; ?><?php echo $content_sticky; ?>">
     <div class="alert alert-warning" role="alert">
         <strong><span class="fal fa-bell fa-lg" aria-hidden="true">
         </span> <?php _e('No products found!','dina-kala') ?></strong>
      </div>
    </div>
<?php }

//Remove Favorite button product archive pages
if ( class_exists( 'JVM_WooCommerce_Wishlist' ) ) {
    remove_action( 'woocommerce_after_shop_loop_item', 'jvm_woocommerce_add_to_wishlist', 15 );
    remove_action( 'woocommerce_after_add_to_cart_button', 'jvm_woocommerce_add_to_wishlist' );
}

//Remove Compare button product archive pages
if (defined( 'WCCM_VERISON' )) {
    remove_action( 'woocommerce_before_shop_loop', 'wccm_register_add_compare_button_hook' );
    remove_action( 'woocommerce_single_product_summary', 'wccm_add_single_product_compare_buttton', 35 );
    remove_action( 'woocommerce_before_shop_loop', 'wccm_render_catalog_compare_info' );
    remove_action( 'wp_enqueue_scripts', 'wccm_enqueue_catalog_scripts' );
    remove_action( 'widgets_init', 'wccm_widgets_init' );
}

//Ajax Load More
if($di_data['ajax_prod']){
add_action('woocommerce_after_shop_loop', 'dina_product_load_more', 11);
}
function dina_product_load_more() { ?>
<div class="col-12 load-more">
	<div class="page-load-status">
		<p class="infinite-scroll-request"><i class="fal fa-spinner-third fa-spin" aria-hidden="true"></i></p>
		<p class="infinite-scroll-last alert alert-info"><?php _e('End of products','dina-kala') ?></p>
		<p class="infinite-scroll-error alert alert-info"><?php _e('No more pages to load','dina-kala') ?></p>
	</div>
	<span id="load-more-button" class="btn btn-outline-dina"><?php _e('Load More Products','dina-kala') ?></span>
</div>
<?php }

//Option to remove product sku
if(!$di_data['show_prod_sku']) {
    add_filter( 'wc_product_sku_enabled', 'dina_remove_product_page_skus' );
}
function dina_remove_product_page_skus( $enabled ) {
    if ( ! is_admin() && is_product() ) {
        return false;
    }
    return $enabled;
}

//Remove download item from woo menu
if($di_data['remove_download']) {
    add_filter( 'woocommerce_account_menu_items', 'remove_my_account_download_items' );
}
function remove_my_account_download_items( $items ) {
    unset($items['downloads']);
    return $items;
}

//remove or change reset variations text
if($di_data['remove_clear_option']) {
    add_filter('woocommerce_reset_variations_link', '__return_empty_string');
} else {
    add_action( 'woocommerce_reset_variations_link' , 'dina_change_clear_text', 15 );
}
function dina_change_clear_text() {
   global $di_data;
   $reset_var_text = ($di_data['ch_reset_var_text']? $di_data['reset_var_text'] : __( 'Clear options', 'dina-kala' ));
   echo '<a class="reset_variations" rel="nofollow" href="#">' . $reset_var_text . '</a>';
}

//Ajax add to cart on archives
function dina_add_to_cart( $product ) {
    global $di_data;
    if(!$di_data['show_hover_btns']) 
         return;
    $coming = get_post_meta( $product->get_id(), 'dina_coming', true );
    if( show_login_price() || !$product->is_purchasable() || !$product->is_in_stock() || $coming || ( !$product->is_type( 'variable' ) && $di_data['show_zero_call'] && ('' === $product->get_price() || 0 == $product->get_price()) ) ) { ?>
        <a href="<?php the_permalink(); ?>" class="btn btn-success btn-buy<?php if( $di_data['show_hover_btns_fixed'] ) { echo ' btn-buy-fixed'; } ?> button">
            <i class="fal fa-eye" aria-hidden="true"></i>
            <?php _e( 'View Product', 'dina-kala' ); ?>
	    </a>
    <?php } elseif(get_option( 'woocommerce_enable_ajax_add_to_cart' ) === 'yes') {
        echo sprintf( '<a href="%s" data-quantity="1" class="%s" %s>%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( implode( ' ', array_filter( array(
                'btn', 'btn-success', 'btn-buy', 'button', 'product_type_' . $product->get_type(),
                $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
                $di_data['show_hover_btns_fixed'] ? ' btn-buy-fixed' : '',
                $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
            ) ) ) ),
            wc_implode_html_attributes( array(
                'data-product_id'  => $product->get_id(),
                'data-product_sku' => $product->get_sku(),
                'aria-label'       => $product->add_to_cart_description(),
                'rel'              => 'nofollow',
            ) ),
            esc_html( $product->add_to_cart_text() )
        );
    } else { ?>
        <a href="<?php the_permalink(); ?>" class="btn btn-success btn-buy<?php if( $di_data['show_hover_btns_fixed'] ) { echo ' btn-buy-fixed'; } ?> button">
            <i class="fal fa-cart-plus" aria-hidden="true"></i>
            <?php _e( 'View And Buy', 'dina-kala' ); ?>
	    </a>
    <?php
    }
}

//Modify Woocommerce query for showing onsale / instock products
/*function dina_woo_pre_get_posts_query( $query_args ) {
    $onsale = isset($_GET['onsale']) ? sanitize_text_field($_GET['onsale']) :"";
    $stock_status = isset($_GET['stock_status']) ? sanitize_text_field($_GET['stock_status']) :"";
    if($onsale){
        $meta_query = (array) $query_args->get( 'meta_query' );
        $meta_query[] =  array(
                array(
                'key' => '_stock_status',
                'value' => 'instock',
                'compare' => '=',
                )
        );
        $query_args->set( 'meta_query', $meta_query );
        $post__in = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
        $query_args->set( 'post__in', $post__in );
    }
    if($stock_status){
        $tax_query = (array) $query_args->get( 'tax_query' );
        $tax_query[] = array(
            'taxonomy' => 'product_visibility',
            'field' => 'name',
            'terms' => 'outofstock',
            'operator' => 'NOT IN',
        );
        $query_args->set( 'tax_query', $tax_query );
    }
}
add_action( 'woocommerce_product_query', 'dina_woo_pre_get_posts_query',99 );*/

function dina_mini_product_classes($id){
    global $di_data;
    $product = wc_get_product( $id );
    $class = "woocommerce shadow-box ".$di_data['prod_hover']." mini-product". ' product-'.$id;
    $class .= ('' === $product->get_price() || 0 == $product->get_price() ? ' zero-prod' : '' );
    $class .= ( $product->is_in_stock() ? '' : ' prod-out-stock' );
    $class .= ( $product->is_type( 'variable' ) ? ' prod-variable' : '' );
    $class .= ( !$di_data['remove_price_range'] ? ' prod-remove-range' : '' );
    $class .= ( get_post_meta( $product->get_id(), 'dina_coming', true ) ? ' prod-coming' : '' );
    $class .= ( show_login_price() ? 'dina-login-price' : '' );
    
    if($di_data['show_sec_img']) {
        $attachment_ids = $product->get_gallery_image_ids();
        if ( is_array( $attachment_ids ) && !empty($attachment_ids) ) {
            $class .= ' hover-image';
        }
    }
    return $class;
}

//Dina Check Sidebar
function dina_check_side(){
    global $di_data;
    $post_id = get_the_ID();
    $side = 0;
    $pside = get_post_meta( $post_id, 'dina_pside', true );
    $postside = get_post_meta( $post_id, 'dina_postside', true );
    $pageside = get_post_meta( $post_id, 'dina_pageside', true );
    $ticket_page = 0;
    $aff_page = 0;
    $dokan_page = 0;
    if( class_exists( 'WeDevs_Dokan' ) ){
        if( $post_id === dokan_get_option( 'dashboard', 'dokan_pages' ) ) {
            $dokan_page = 1;
        } 
    }
    if( class_exists( 'Awesome_Support' ) ) { 
        $ticket_id = wpas_get_option( 'ticket_list' );
        $ticket_submit_id = wpas_get_option( 'ticket_submit' );
        if(is_array($ticket_submit_id)){
            $ticket_submit = $ticket_submit_id[0];
        }
        else{
            $ticket_submit = $ticket_submit_id;
        }
        if( ($post_id === (int)$ticket_id) || ($post_id === (int)$ticket_submit) ) {
            $ticket_page = 1; 
        } 
    }
    if( class_exists( 'Affiliate_WP' ) ) { 
        if( $post_id === affwp_get_affiliate_area_page_id() ) {
            $aff_page = 1;
        }
    }
    if((is_woocommerce() && is_archive()) && $di_data['product_archive_side'] != 0) {
        $side = 2;
    } elseif((is_woocommerce() && is_archive()) && $di_data['product_archive_side'] == 0) {
        $side = 0;
    } elseif(is_page_template() || is_account_page() || $dokan_page == 1 || $aff_page == 1 || $ticket_page == 1){
        $side = 0;
    } elseif(is_single() && 'post' == get_post_type() && $postside != 'wside') {
        $side = 1;
    } elseif(is_single() && 'product' == get_post_type() && $pside != 'wside') {
        if(($pside == 'rside' || $pside == 'lside') && $pside != 'wside') {
            $side = 1;
        } elseif($di_data['product_side'] > 0 && $pside != 'wside') {
            $side = 1;
        }
    } elseif(is_page() && $pageside != 'wside'){
        $side = 1;
    } elseif(is_archive() && $di_data['post_archive_side'] != 0){
        $side = 1;
    }
    return $side;
}

//Remove Select2 for WooCommerce
add_action('wp_enqueue_scripts', 'wc_disable_select2', 100);
function wc_disable_select2() {
    if ( class_exists('woocommerce') ) {
        if(is_woocommerce() && is_archive())
        {
            wp_dequeue_style('select2');
            wp_deregister_style('select2');
    
            // WooCommerce 3.2.1.x and below
            wp_dequeue_script('select2');
            wp_deregister_script('select2');
    
            // WooCommerce 3.2.1+
            wp_dequeue_script('selectWoo');
            wp_deregister_script('selectWoo');
        }
    } 
}

//Dina_product_rating
function dina_product_rating($id){
    global $di_data;
    $product = wc_get_product( $id );

    if ( ! wc_review_ratings_enabled() || !$di_data['show_star_rating'] ) {
        return;
    }

    $rating_count = $product->get_rating_count();
    $review_count = $product->get_review_count();
    $average      = $product->get_average_rating();

    if ( $rating_count > 0 ) {
        echo '<div class="woocommerce-product-rating">';
        echo wc_get_rating_html( $average, $rating_count );
        echo '</div>';
    }
}

//Dina_check_product_purchasable
function dina_check_product_purchasable(){
    global $di_data;
    global $product;
    $coming = get_post_meta( get_the_id(), 'dina_coming', true );
    if(!$product->is_purchasable() || !$product->is_in_stock() || $coming || ( $di_data['show_zero_call'] && ('' === $product->get_price() || 0 == $product->get_price()) )) { 
        return false;
    } else{
        return true;
    }
}

//Get product deeper category
function dina_get_prod_deep_cats($product_id) {
    $prod_deep_cat = '';
    // get all product cats for the current post
    $categories = get_the_terms( $product_id, 'product_cat' ); 

    // wrapper to hide any errors from top level categories or products without category
    if ( $categories ) : 
        // loop through each cat
        $cats = array();
        foreach($categories as $category) :
        // get the children (if any) of the current cat
        $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));

        if ( count($children) == 0 ) {
            // if no children, then echo the category name.
            $cats[] = $category->term_id;
        }
        endforeach;
    endif;

    return $cats;
}

//Get terms link
function dina_get_term_links($term_tax,$term_ids) {
    if (is_array($term_ids))
    {	
        if(count($term_ids) == 1) {
            $term_link = get_term_link((int)$term_ids[0],$term_tax);
        } else {
            $term_link = get_home_url() . '/?'.$term_tax.'=';
            foreach($term_ids as $id) {
                $term = get_term( $id, $term_tax );
                $slug = $term->slug;
                $term_link.= $slug . ',';
            }
        }
    } else {
        $term_link = get_term_link((int)$term_ids,$term_tax);
    }
    return $term_link;
}

//Remove password strength check.
if($di_data['remove_password_strength']) {
    add_action( 'wp_print_scripts', 'di_remove_password_strength', 10 );
}
function di_remove_password_strength() {
    wp_dequeue_script( 'wc-password-strength-meter' );
}

//Add archive title to woocommerce archive pages
if($di_data['show_archive_title']) {
    add_action('woocommerce_before_main_content', 'dina_woo_archive_title',20);
}
function dina_woo_archive_title() {
   global $di_data;
   $show_archive_mobile = ( $di_data['show_archive_title_mobile'] ? '' : ' mobile-hidden' );
   if(is_woocommerce() && is_archive()) {
       echo '<div class="row archive-title-con'. $show_archive_mobile .'"><div class="col-12 shadow-box"><h1>';
           woocommerce_page_title();
       echo '</h1></div></div>';
   }
}

//Poduct archive hover
function dina_prod_hover($product_id) {
    if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
        return;
    }
    if ( \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
        return;
    }
    global $di_data; ?>

    <span class="prod-hover-btns">

        <?php if ( $di_data['show_quick_view'] ) { ?>
            <span data-dina-product-id="<?php echo $product_id; ?>" data-toggle="tooltip" data-placement="right" data-delay='{"show":"500", "hide":"0"}' class="quick-view-btn prod-hover-btn btn btn-light" title="<?php _e('Quick View', 'dina-kala'); ?>">
                <i class="fal fa-eye" aria-hidden="true"></i>
            </span>
        <?php } ?>

        <?php if ( $di_data['like_prod_archive'] ) {
            if( class_exists('YITH_WCWL') ) { ?>
                <span data-toggle="tooltip" data-placement="right" data-delay='{"show":"500", "hide":"0"}' class="like-prod-btn dina-yith-wcwl prod-hover-btn btn btn-light" title="<?php echo __('Add to Wishlist', 'dina-kala'); ?>">
                    <?php echo preg_replace("/<img[^>]+\>/i", " ", do_shortcode('[yith_wcwl_add_to_wishlist]')); ?>
                </span>
            <?php } elseif ( class_exists( 'JVM_WooCommerce_Wishlist' ) ) { ?>
                <span data-toggle="tooltip" data-placement="right" data-delay='{"show":"500", "hide":"0"}' class="like-prod-btn prod-hover-btn btn btn-light" title="<?php echo __('Add to Wishlist', 'dina-kala'); ?>">
                <?php echo do_shortcode('[jvm_woocommerce_add_to_wishlist]'); ?>
                </span>
        <?php }
        } ?>
        
        <?php if ( $di_data['compare_prod_archive'] ) { 
            if( class_exists('YITH_Woocompare') ) { ?>
            <div class="dina-compare-button prod-hover-btn btn btn-light" data-toggle="tooltip" data-placement="right" data-delay='{"show":"500", "hide":"0"}' title="<?php _e('Compare Product', 'dina-kala'); ?>">
                <?php echo do_shortcode('[yith_compare_button]'); ?>
            </div>
        <?php } elseif( defined( 'WCCM_VERISON' ) ) { ?>
            <?php 
            if ( in_array( $product_id, wccm_get_compare_list() ) ) {
                $compare_title= __('Remove From Compare', 'dina-kala');
                $compare_class = " in-compare";
            } else {
                $compare_title= __('Compare Product', 'dina-kala');
                $compare_class = "";
            }
            ?>
            <span data-dina-compare-id="<?php echo $product_id; ?>" data-toggle="tooltip" data-placement="right" data-delay='{"show":"500", "hide":"0"}' class="compare-ajax-btn prod-hover-btn btn btn-light<?php echo $compare_class; ?>" title="<?php echo $compare_title; ?>">
                <i class="fal fa-random" aria-hidden="true"></i>
            </span>
        <?php }
        } ?>

    </span>
<?php }

//WooCommerce Show Product Image at Checkout Page
add_filter( 'woocommerce_cart_item_name', 'dina_product_image_on_checkout', 10, 3 );
function dina_product_image_on_checkout( $name, $cart_item, $cart_item_key ) {
    /* Return if not checkout page */
    if ( ! is_checkout() ) {
        return $name;
    }
    /* Get product object */
    $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
    /* Get product thumbnail */
    $thumbnail = $_product->get_image('thumbnail');
    $image = '<div class="dina-ch-product-image">'
                . $thumbnail .
            '</div>'; 
    /* Prepend image to name and return it */
    return $image . $name;
}

//Dina before cart
add_action('woocommerce_before_cart', 'dina_before_cart');
function dina_before_cart() {
    echo '<div class="dina-cart-content-wrapper row">';
}

//Dina after cart
add_action('woocommerce_after_cart', 'dina_after_cart');
function dina_after_cart() {  
    echo '</div>';
}

//Dina empty cart
add_action('woocommerce_cart_is_empty', 'dina_empty_cart');
function dina_empty_cart() { ?>
    <div class="dina-empty-cart">
        <i class="fal fa-shopping-cart empty-cart-icon" aria-hidden="true"></i>
        <div class="dina-empty-cart-text">
            <?php _e('Before proceed to checkout you must add some products to your shopping cart.', 'dina-kala'); ?>
            <br>
            <?php _e('You will find a lot of interesting products on our "Shop" page.', 'dina-kala'); ?>
        </div>
    </div>
<?php }

//Add Affiliate link to my account page
if( class_exists( 'Affiliate_WP' ) ) {
    add_filter ( 'woocommerce_account_menu_items', 'affiliate_one_more_link' );
    function affiliate_one_more_link( $menu_links ){
        // we will hook "affiliate-wp" later
        $new = array( 'affiliate-wp' => __('Affiliates' , 'dina-kala') ); 
        // or in case you need 2 links
        // $new = array( 'link1' => 'Link 1', 'link2' => 'Link 2' );
    
        // array_slice() is good when you want to add an element between the other ones
        $menu_links = array_slice( $menu_links, 0, 5, true ) 
        + $new 
        + array_slice( $menu_links, 1, NULL, true );
        return $menu_links;
    }
    add_filter( 'woocommerce_get_endpoint_url', 'affiliate_hook_endpoint', 5, 4 );
    function affiliate_hook_endpoint( $url, $endpoint, $value, $permalink ){
        if( $endpoint === 'affiliate-wp' ) {
            // ok, here is the place for your custom URL, it could be external
            $url = esc_url( affwp_get_affiliate_area_page_url() );
        }
        return $url;
    }
}

//
remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display', 10 );
add_action( 'woocommerce_before_cart_collaterals', 'woocommerce_cross_sell_display', 10 );

//Dina Product Label
add_action('woocommerce_product_thumbnails' , 'dina_product_label' );
function dina_product_label($id) {

    //if(empty($id)) {
        global $product;
        $id = $product->get_id();
    //}

    $plabel = get_post_meta( $id, 'dina_plabel', true );
    $plabel_color = get_post_meta( $id, 'dina_plabel_color', true );

    if(!empty($plabel)) {
        $product_label ='<span class="product-label product-label-'.$plabel_color.'">'. $plabel .'</span>';
    } else {
        $product_label = '';
    }
    echo $product_label;

}

//Show price to logged in users
function show_login_price() {
    global $di_data;
    if ( !is_user_logged_in() && $di_data['show_login_price'] ) 
        return true;
}

//Show Product Categori's Sub Categorie
function dina_show_sub_cats() {
    global $di_data;
    $term_id  = get_queried_object_id();
        $taxonomy = 'product_cat';
    
        // Get subcategories of the current category
        $terms    = get_terms([
            'taxonomy'    => $taxonomy,
            'hide_empty'  => true,
            'parent'      => get_queried_object_id()
        ]);

        if ( empty($terms ) ) 
        return;
        $mobile_cats = ( !$di_data['show_sub_cats_mobile'] ? ' dina-hide-cats-mobile' : '' );
        $output = '<div class="row dina-sub-cat-row'. $mobile_cats .'">
        <div class="col-12 shadow-box dina-sub-cats">
            <div class="dina-subcat-list-title">'. __( 'Subcategories' , 'dina-kala' ) .'</div>';
        $rtl = ( is_rtl() ? 'true' : 'false');
        $output .= '<ul class="dina-subcat-list owl-carousel" data-dir="'. $rtl .'">';
    
        // Loop through product subcategories WP_Term Objects
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, $taxonomy );
            $thumbnail_id = get_term_meta ( $term->term_id, 'thumbnail_id', true );
            $image_attributes = wp_get_attachment_image_src( $thumbnail_id );
            $cat_img = ( !empty( $image_attributes[0] ) ? $image_attributes[0] : esc_url( get_template_directory_uri() ) . '/images/mtumb.png' );
            $output .= '<li class="dina-cat-thumb item '. $di_data['prod_hover'] .'">
                                <a class="dina-cat-link" href="'. $term_link .'" title="'. $term->name .'">
                                    <div class="dina-cat-img-con">
                                        <img width="150" height="150" src="'. $cat_img .'" class="dina-cat-img" alt="'. $term->name .'">
                                    </div>
                                    <span class="dina-cat-title">'. $term->name .'</span>
                                </a>
                        </li>';
        }

        $output . '</ul>';

        $output .= '</div></div>';
    
        echo $output;
}

remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close' );
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' ); 

if ( ! function_exists( 'dina_widget_get_current_page_url' ) ) {
	function dina_widget_get_current_page_url( $link ) {
		if ( isset( $_GET['stock_status'] ) ) {
			$link = add_query_arg( 'stock_status', wc_clean( $_GET['stock_status'] ), $link );
		}

        if ( isset( $_GET['product_brand'] ) ) {
			$link = add_query_arg( 'product_brand', wc_clean( $_GET['product_brand'] ), $link );
		}

		return $link;
	}

	add_filter( 'woocommerce_widget_get_current_page_url', 'dina_widget_get_current_page_url' );
}

//Dina Get base shop page link
if ( ! function_exists( 'dina_shop_page_link' ) ) {
	function dina_shop_page_link( $keep_query = false, $taxonomy = '' ) {
		// Base Link decided by current page
		$link = '';
        
		if ( class_exists( 'Automattic\Jetpack\Constants' ) && Automattic\Jetpack\Constants::is_defined( 'SHOP_IS_ON_FRONT' ) ) {
			$link = home_url();
		} elseif ( is_post_type_archive( 'product' ) || is_page( wc_get_page_id( 'shop' ) ) || is_shop() ) {
			$link = get_permalink( wc_get_page_id( 'shop' ) );
		} elseif ( is_product_category() ) {
			$link = get_term_link( get_query_var( 'product_cat' ), 'product_cat' );
		} elseif ( is_product_tag() ) {
			$link = get_term_link( get_query_var( 'product_tag' ), 'product_tag' );
		} elseif ( get_queried_object() ) {
			$queried_object = get_queried_object();

			if ( property_exists( $queried_object, 'taxonomy' ) ) {
				$link = get_term_link( $queried_object->slug, $queried_object->taxonomy );
			}
		}

		if ( $keep_query ) {

			// Min/Max
			if ( isset( $_GET['min_price'] ) ) {
				$link = add_query_arg( 'min_price', wc_clean( $_GET['min_price'] ), $link );
			}

			if ( isset( $_GET['max_price'] ) ) {
				$link = add_query_arg( 'max_price', wc_clean( $_GET['max_price'] ), $link );
			}

			// Orderby
			if ( isset( $_GET['orderby'] ) ) {
				$link = add_query_arg( 'orderby', wc_clean( $_GET['orderby'] ), $link );
			}

			if ( isset( $_GET['stock_status'] ) ) {
				$link = add_query_arg( 'stock_status', wc_clean( $_GET['stock_status'] ), $link );
			}

            if ( isset( $_GET['product_brand'] ) ) {
				$link = add_query_arg( 'product_brand', wc_clean( $_GET['product_brand'] ), $link );
			}

			if ( isset( $_GET['per_row'] ) ) {
				$link = add_query_arg( 'per_row', wc_clean( $_GET['per_row'] ), $link );
			}

			if ( isset( $_GET['per_page'] ) ) {
				$link = add_query_arg( 'per_page', wc_clean( $_GET['per_page'] ), $link );
			}

			if ( isset( $_GET['shop_view'] ) ) {
				$link = add_query_arg( 'shop_view', wc_clean( $_GET['shop_view'] ), $link );
			}

			if ( isset( $_GET['shortcode'] ) ) {
				$link = add_query_arg( 'shortcode', wc_clean( $_GET['shortcode'] ), $link );
			}

			/**
			 * Search Arg.
			 * To support quote characters, first they are decoded from &quot; entities, then URL encoded.
			 */
			if ( get_search_query() ) {
				$link = add_query_arg( 's', rawurlencode( wp_specialchars_decode( get_search_query() ) ), $link );
			}

			// Post Type Arg
			if ( isset( $_GET['post_type'] ) ) {
				$link = add_query_arg( 'post_type', wc_clean( wp_unslash( $_GET['post_type'] ) ), $link );

				// Prevent post type and page id when pretty permalinks are disabled.
				if ( is_shop() ) {
					$link = remove_query_arg( 'page_id', $link );
				}
			}

			// Min Rating Arg
			if ( isset( $_GET['min_rating'] ) ) {
				$link = add_query_arg( 'min_rating', wc_clean( $_GET['min_rating'] ), $link );
			}

			// All current filters
			if ( $_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes() ) {
				foreach ( $_chosen_attributes as $name => $data ) {
					if ( $name === $taxonomy ) {
						continue;
					}
					$filter_name = sanitize_title( str_replace( 'pa_', '', $name ) );
					if ( ! empty( $data['terms'] ) ) {
						$link = add_query_arg( 'filter_' . $filter_name, implode( ',', $data['terms'] ), $link );
					}
					if ( 'or' == $data['query_type'] ) {
						$link = add_query_arg( 'query_type_' . $filter_name, 'or', $link );
					}
				}
			}
		}

		$link = apply_filters( 'dina_shop_page_link', $link, $keep_query, $taxonomy );

		if ( is_string( $link ) ) {
			return $link;
		} else {
			return '';
		}
	}
}

//Dina shop filter query
add_action( 'woocommerce_product_query', 'dina_shop_filter_query' );
if ( ! function_exists( 'dina_shop_filter_query' ) ) {
    function dina_shop_filter_query( $q ){
    
    if( ( ( is_woocommerce() && is_archive() ) || is_shop() ) ) {
    
        $current_stock_status = isset( $_GET['stock_status'] ) ? explode( ',', $_GET['stock_status'] ) : array();
        $product_brand = isset( $_GET['product_brand'] ) ? explode( ',', $_GET['product_brand'] ) : array();
            
            if( in_array( 'onsale', $current_stock_status ) ) {
                $product_ids_on_sale = wc_get_product_ids_on_sale();
                $q->set( 'post__in', $product_ids_on_sale );
            }

            if( in_array( 'instock', $current_stock_status ) ) {
                $query_array = array(
                    'relation' => 'AND',
                    array(
                        'key' => '_stock_status',
                        'value' => 'instock',
                        'compare' => '=',
                    )
                );
                $q->set( 'meta_query', $query_array );
            }

            if( !empty( $product_brand ) ) {
                $tax_query = array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'brand',
                        'field' => 'term_id',
                        'terms' => $product_brand,
                    )
                );
                $q->set( 'tax_query', $tax_query );
            }
        }
    }
}