<?php
require_once get_parent_theme_file_path( '/inc/mobmenu_walker.php' );
require_once get_parent_theme_file_path( '/inc/theme-color.php' );

//Option tree panel settings
require( trailingslashit( get_template_directory() ) . 'option-tree/ot-loader.php' );
require( trailingslashit( get_template_directory() ) . 'inc/theme-options.php' );
add_filter( 'ot_show_pages', '__return_false' );

//Gajcommerce register menu
function menusgc() {
  register_nav_menus(
    array(
      'header-menu' => __( 'Main menu' , 'gajcommerce' ),
      'mobile-menu' => __( 'Mobile menu' , 'gajcommerce' ),
      'footer1-menu' => __( 'First footer menu' , 'gajcommerce' ),
      'footer2-menu' => __( 'Second footer menu' , 'gajcommerce' ),
      'footer3-menu' => __( 'Third footer menu' , 'gajcommerce' ),
    )
  );
}
add_action( 'init', 'menusgc' );

//Gajcommerce register widgets
function widgetsgc() {

	register_sidebar( array(
		'name'          => __('Main sidebar' , 'gajcommerce'),
		'id'            => 'sideallgc',
		'before_widget' => '<div class="sidebox %2$s">',
		'after_widget'  => '</section></div>',
		'before_title'  => '<header><p>',
		'after_title'   => '</p></header><section>',
	) );

  register_sidebar( array(
		'name'          => __('Shop sidebar' , 'gajcommerce'),
		'id'            => 'sideshopgc',
		'before_widget' => '<div id="%1$s" class="sidebox %2$s">',
		'after_widget'  => '</section></div>',
		'before_title'  => '<header><p>',
		'after_title'   => '</p></header><section>',
	) );

  register_sidebar( array(
		'name'          => __('First footer column' , 'gajcommerce'),
		'id'            => 'firstfootergc',
		'before_widget' => '<div class="footbox">',
		'after_widget'  => '</section></div>',
		'before_title'  => '<header><h3>',
		'after_title'   => '</h3></header><section>',
	) );

  register_sidebar( array(
		'name'          => __('Second footer column' , 'gajcommerce'),
		'id'            => 'sectfootergc',
		'before_widget' => '<div class="footbox">',
		'after_widget'  => '</section></div>',
		'before_title'  => '<header><h3>',
		'after_title'   => '</h3></header><section>',
	) );

  register_sidebar( array(
		'name'          => __('Third footer column' , 'gajcommerce'),
		'id'            => 'trdtfootergc',
		'before_widget' => '<div class="footbox">',
		'after_widget'  => '</section></div>',
		'before_title'  => '<header><h3>',
		'after_title'   => '</h3></header><section>',
	) );

}
add_action( 'widgets_init', 'widgetsgc' );

//Theme supports
add_theme_support( 'post-thumbnails' );
add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );
add_theme_support( 'title-tag' );

//Gajcommerce image sizes
add_image_size( 'side-thumb', 60, 60, true );
add_image_size( 'main-thumb', 190, 190, false );

//Woocommerce support
function gajcommerce_add_woocommerce_support() {
	add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'gajcommerce_add_woocommerce_support' );

//Woocommerce order by stock in archive
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? wc_clean ( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

 if ( 'stock' == $orderby_value ) {
  $args['orderby'] = array( 'meta_value' => 'ASC', 'date' => 'DESC' );
  $args['meta_key'] = '_stock_status';
 }

 return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );

function custom_woocommerce_catalog_orderby( $sortby ) {
 $sortby['stock'] = __('Sort by stock status' , 'gajcommerce');
 return $sortby;
}

//Gajcommerce comments form
function advanced_comment($comment, $args, $depth) {
 $GLOBALS['comment'] = $comment; ?>
 <div class="col-12">
  <div class="commentslist">
    <div class="commentslistbox">
      <?php echo get_avatar( $comment, 75 ); ?>
      <h3><?php echo get_comment_author_link(); ?> در <?php printf(__('%1$s'), get_comment_date('j F Y'), get_comment_time()) ?> <?php _e('Said:' , 'gajcommerce'); ?> </h3>
      <p><?php comment_text(); ?></p>
      <?php if ($comment->comment_approved == '0') : ?>
        <p>
                  <em>دیدگاه شما منتظر تایید مدیریت است.</em><br />
                </p>
              <?php endif; ?>
      <span><?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?></span>
    </div>
  </div>
</div>
<?php }

//Option tree settings
add_filter( 'ot_theme_mode', '__return_true' );
add_filter('ot_theme_options_parent_slug', '__return_false');

//Woocommerce disable single Search
add_filter( 'woocommerce_redirect_single_search_result', '__return_false' );

//Gajcommerce news widget
function wpb_load_widget() {
    register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

class wpb_widget extends WP_Widget {

function __construct() {
parent::__construct(

// Base ID of your widget
'wpb_widget',

// Widget name will appear in UI
__('آخرین مقالات گاج کامرس', 'wpb_widget_domain'),

// Widget description
array( 'description' => __( 'ویجت اختصاصی قالب گاج کامرس برای نمایش آخرین مطالب بلاگ', 'wpb_widget_domain' ), )
);
}

// Creating widget front-end

public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );

// before and after widget arguments are defined by themes
?>
<div class="specialsidebox">
<?php
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
?>
<?php
$specialwidgetgccat=ot_get_option('specialwidgetgccat',false);
$specialwidgetgccount=ot_get_option('specialwidgetgccount','5');
$the_query = new WP_Query( array( 'post_type' => 'post' , 'posts_per_page'=> $specialwidgetgccount , 'category_name'=> $specialwidgetgccat ) ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  <ul>
    <li><a href="<?php echo the_permalink(); ?>"><?php echo the_post_thumbnail( 'side-thumb' ); ?>
        <div class="titlesideeach">
          <?php echo the_title(); ?>
        </div>
        <div class="sidedategm">
          <?php echo the_time('j F Y'); ?>
        </div>
      </a>
    </li>
  </ul>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'متاسفیم، محتوایی پیدا نشد.' ); ?></p>
<?php endif; ?>
<?php if ($specialwidgetgccat!==false) { ?>
<a class="sidectalink" target="_blank" href="<?php echo home_url(); ?>/category/<?php echo $specialwidgetgccat ?>">
  <div class="sidecta">
    <span>مطالب بیشتر</span><i class="fas fa-angle-left"></i></div>
</a>
<?php } elseif (get_option( 'page_for_posts' ) && $specialwidgetgccat===false) { ?>
  <a class="sidectalink" target="_blank" href="<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>">
    <div class="sidecta">
      <span>مطالب بیشتر</span><i class="fas fa-angle-left"></i></div>
  </a>
<?php } else {}?>
<?php
echo $args['after_widget'];
echo '</div>';
}

// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'آخرین مقالات', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>

<?php
}

// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Gajcommerce news widget ends here

//Change number of products that are displayed per page (shop page)
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  $cols = ot_get_option('pdinarchivegc', '9');
  return $cols;
}

/* TGM */
require_once dirname( __FILE__ ) . '/tgm/class-tgm-plugin-activation.php';

add_action( 'tgmpa_register', 'my_theme_register_required_plugins' );

function my_theme_register_required_plugins() {

	$plugins = array(

		array(
			'name'      => 'WooCommerce',
			'slug'      => 'woocommerce',
			'required'  => true,
		),
		array(
			'name'      => 'Persian Woocommerce',
			'slug'      => 'persian-woocommerce',
			'required'  => false,
		),
    array(
			'name'      => 'YITH WooCommerce Wishlist',
			'slug'      => 'yith-woocommerce-wishlist',
			'required'  => false,
		),
		array(
			'name'      => 'WP-PostViews',
			'slug'      => 'wp-postviews',
			'required'  => true,
		),
    array(
			'name'      => 'Ajax Search for WooCommerce',
			'slug'      => 'ajax-search-for-woocommerce',
			'required'  => false,
		),
    array(
			'name'      => 'Elementor Website Builder',
			'slug'      => 'elementor',
			'required'  => true,
		),
    array(
			'name'      => 'Advanced noCaptcha & invisible Captcha',
			'slug'      => 'advanced-nocaptcha-recaptcha',
			'required'  => false,
		),
    array(
			'name'      => 'افزونه مقایسه محصولات',
			'slug'      => 'woocommerce-compare-list',
			'required'  => false,
      'source'    => get_template_directory_uri() . '/tgm/plugins/woocommerce-compare-list.zip',
		),

	);

	$config = array(
		'id'           => 'tgmpa',                 // Unique ID for hashing notices for multiple instances of TGMPA.
		'default_path' => '',                      // Default absolute path to bundled plugins.
		'menu'         => 'tgmpa-install-plugins', // Menu slug.
		'parent_slug'  => 'themes.php',            // Parent menu slug.
		'capability'   => 'edit_theme_options',    // Capability needed to view plugin install page, should be a capability associated with the parent menu used.
		'has_notices'  => true,                    // Show admin notices or not.
		'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
		'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
		'is_automatic' => false,                   // Automatically activate plugins after installation or not.
		'message'      => '',                      // Message to output right before the plugins table.

	);

	tgmpa( $plugins, $config );
}

// Display Price For Variable Product With Same Variations Prices
add_filter('woocommerce_available_variation', function ($value, $object = null, $variation = null) {
    if ($value['price_html'] == '') {
        $value['price_html'] = '<span class="price">' . $variation->get_price_html() . '</span>';
    }
    return $value;
}, 10, 3);

// WordPress Custom Font @ Admin
function gajcommerce_admin_font() {
    $gajcommerce_directory=get_template_directory_uri();
    echo '<link href="' . $gajcommerce_directory . '/fonts/fonts.css" rel="stylesheet">' . PHP_EOL;
    echo '<style>body.rtl, .editor-post-title__block .editor-post-title__input, .editor-styles-wrapper, .components-base-control, .rtl h1, .rtl h2, .rtl h3, .rtl h4, .rtl h5, .rtl h6, #wpadminbar *:not([class="ab-icon"]), .wp-core-ui, .media-menu, .media-frame *, .media-modal *{font-family: IRANSans !important;}.widefat thead tr th{padding:0!important}</style>' . PHP_EOL;
}
add_action( 'admin_head', 'gajcommerce_admin_font' );

// WordPress Custom Font @ Admin Frontend Toolbar
function gajcommerce_font_frontend_toolbar() {
    if(current_user_can('administrator')) {
        $gajcommerce_directory=get_template_directory_uri();
        echo '<link href="' . $gajcommerce_directory . '/fonts/fonts.css" rel="stylesheet">' . PHP_EOL;
        echo '<style>#wpadminbar *:not([class="ab-icon"]){font-family: IRANSans !important;}</style>' . PHP_EOL;
    }
}
add_action( 'wp_head', 'gajcommerce_font_frontend_toolbar' );

// WordPress Custom Font @ Admin Login
function gajcommerce_font_login_page() {
    if(stripos($_SERVER["SCRIPT_NAME"], strrchr(wp_login_url(), '/')) !== false) {
        $gajcommerce_directory=get_template_directory_uri();
        echo '<link href="' . $gajcommerce_directory . '/fonts/fonts.css" rel="stylesheet">' . PHP_EOL;
        echo '<style>body{font-family: IRANSans !important;}</style>' . PHP_EOL;
	}
}
add_action( 'login_head', 'gajcommerce_font_login_page' );

//javascript for plus minus add to cart button
add_action( 'wp_footer', 'bbloomer_add_cart_quantity_plus_minus' );

function bbloomer_add_cart_quantity_plus_minus() {

   if ( ! is_product() && ! is_cart() ) return;

   wc_enqueue_js( "

   $(document).on('click','button.plus, button.minus',function(e){

var qty = $( this ).parent( '.quantity' ).find( '.qty' );
var val = parseFloat(qty.val());
var max = parseFloat(qty.attr( 'max' ));
var min = parseFloat(qty.attr( 'min' ));
var step = parseFloat(qty.attr( 'step' ));

$('.woocommerce .actions button.button').prop('disabled', false);

if ( $( this ).is( '.plus' ) ) {
   if ( max && ( max <= val ) ) {
      qty.val( max );
   } else {
      qty.val( val + step );
   }
} else {
   if ( min && ( min >= val ) ) {
      qty.val( min );
   } else if ( val > 1 ) {
      qty.val( val - step );
   }
}
});

   " );
}

//Auto update cart total price after changing cart items quantity
add_action('wp_footer' , 'gajcommerce_auto_cart_update_qty');
function gajcommerce_auto_cart_update_qty() {
  if ( is_cart() ) { ?>
    <script type="text/javascript">
      var timeout;

      jQuery( function( $ ) {
      	$('.woocommerce').on('click', 'button.plus , button.minus', function(){

      		if ( timeout !== undefined ) {
      			clearTimeout( timeout );
      		}

      		timeout = setTimeout(function() {
      			$("[name='update_cart']").trigger("click");
      		}, 1000 ); // 1 second delay, half a second (500) seems comfortable too

      	});
      } );
    </script>
<?php
  }
}

//Disable download menu from my-account page
function gc_dl_disable() {
  if ( 'off' === ot_get_option('gcdlmenuonoff', false) ) {
    function daynaweb_gajcommerce_dl_disable( $items ) {
      unset($items['downloads']);
      return $items;
    }
    add_filter( 'woocommerce_account_menu_items', 'daynaweb_gajcommerce_dl_disable' );
  }
}
add_action( 'after_setup_theme', 'gc_dl_disable', 2 );

//Add users profile pic to my-account page
function action_woocommerce_before_account_navigation(  ) {
  global $current_user;
    echo '<div class="gc-myacc-top-nav"><div class="gc-myacc-top-nav-inner">' . get_avatar( $current_user->ID, 80 ) . 'سلام' . '&nbsp;' . $current_user->display_name . '&nbsp;عزیز!' . '</div></div>';
};

add_action( 'woocommerce_before_account_navigation', 'action_woocommerce_before_account_navigation', 10, 0 );

//Disable Dokan`s default more products tab and create custom table
if( class_exists( 'WeDevs_Dokan' ) ) {

  add_filter( 'woocommerce_product_tabs', 'wcs_woo_remove_more_seller_product_tab', 98 );
      function wcs_woo_remove_more_seller_product_tab($tabs) {
      unset($tabs['more_seller_product']);
      return $tabs;
  }

  function dokan_get_more_products_from_seller_custom( $seller_id = 0, $posts_per_page = 6 ) {

      global $product, $post;

      if ( $seller_id == 0 ) {
          $seller_id = $post->post_author;
      }

      if ( ! abs( $posts_per_page ) ) {
          $posts_per_page = 4;
      }

      $args = array(
          'post_type'      => 'product',
          'posts_per_page' => $posts_per_page,
          'orderby'        => 'rand',
          'post__not_in'   => array( $post->ID ),
          'author'         => $seller_id,
      );

      $products = new WP_Query( $args );?>
      <div class="row">

      <?php

      if ( $products->have_posts() ) {
          woocommerce_product_loop_start();

          while ( $products->have_posts() ) {
              $products->the_post();

              wc_get_template_part( 'content', 'dokan' );
          }

          woocommerce_product_loop_end();
      } else {
          esc_html_e( 'No product has been found!', 'dokan-lite' );
      }?>
      </div>
<?php

      wp_reset_postdata();
  }

  function dokan_set_more_from_seller_tab_custom( $tabs ) {
      if ( check_more_seller_product_tab() ) {
          $tabs['more_seller_product_custom'] = array(
              'title'     => __( 'More Products', 'dokan-lite' ),
              'priority'  => 99,
              'callback'  => 'dokan_get_more_products_from_seller_custom',
          );
      }
      return $tabs;
}

  add_action( 'woocommerce_product_tabs', 'dokan_set_more_from_seller_tab_custom', 10 );

}

//Redirect users to myaccount after register
function daynaweb_custom_registration_redirect() {
    return get_permalink( wc_get_page_id( 'myaccount' ) );
}
add_action('woocommerce_registration_redirect', 'daynaweb_custom_registration_redirect', 2);

//Redirect users to myaccount after login
function daynaweb_custom_login_redirect() {
  return get_permalink( wc_get_page_id( 'myaccount' ) );
}
add_filter('woocommerce_login_redirect', 'daynaweb_custom_login_redirect');

//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' );
}

//Yoast seo compatibility
add_filter( 'wpseo_remove_reply_to_com', '__return_false' );

//Gajcommerce breadcrumb
function the_breadcrumb() {
    $sep = ' / ';
    if (!is_front_page()) {

	// Start the breadcrumb with a link to your homepage
        echo '<div class="breadcrumbb">';
        echo '<a href="';
        echo get_option('home');
        echo '">';
        echo 'صفحه اصلی';
        echo '</a>' . $sep;

	// Check if the current page is a category, an archive or a single page. If so show the category or archive name.
        if (is_category() || is_single() ){
            the_category(' / ');
        } elseif (is_archive() || is_single()){
            if ( is_day() ) {
                printf( __( '%s', 'text_domain' ), get_the_date() );
            } elseif ( is_month() ) {
                printf( __( '%s', 'text_domain' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'text_domain' ) ) );
            } elseif ( is_year() ) {
                printf( __( '%s', 'text_domain' ), get_the_date( _x( 'Y', 'yearly archives date format', 'text_domain' ) ) );
            } else {
              single_tag_title();
                _e( ' &nbsp;&nbsp;', 'text_domain' );
            }
        }

	// If the current page is a single post, show its title with the separator
        if (is_single()) {
            echo $sep;
            echo '<span>';
            the_title();
            echo '</span>';
        }

	// If the current page is a static page, show its title.
        if (is_page()) {
            echo the_title();
            echo "&nbsp;&nbsp;";
        }

	// if you have a static page assigned to be you posts list page. It will find the title of the static page and display it. i.e Home >> Blog
        if (is_home()){
            global $post;
            $page_for_posts_id = get_option('page_for_posts');
            if ( $page_for_posts_id ) {
                $post = get_page($page_for_posts_id);
                setup_postdata($post);
                the_title();
                rewind_posts();
            }
        }
        echo '</div>';
    }
}

//Gajcommerce farsi numbers
function gajcommerce_change_number($num) {
    $eng = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    $per = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    return str_replace($eng, $per, $num);
}

//Products archive pages h1 title
function gajcommerce_archive_product_h1_title() {
  global $product;
  echo '<h1 class="gc-archive-product-h1">' . single_term_title('', false) . '</h1>';
}
add_action('woocommerce_before_shop_loop' , 'gajcommerce_archive_product_h1_title');

//Register custom flexslider codes for single product gallery
add_action( 'wp_footer', 'gajcommerce_vcrtl_conflict', 11 );
function gajcommerce_vcrtl_conflict() {
    if (defined('WPB_VC_VERSION')) {
        wp_deregister_script( 'flexslider' );
        wp_enqueue_script('flexslider', get_template_directory_uri() . '/js/jquery.flexslider.min.js', array('jquery'), true);
    }
}

//Js for single product gallery slider
add_action( 'wp_footer', 'gajcommerce_js_custom_product_gallery' );
function gajcommerce_js_custom_product_gallery() {
  if( is_singular('product') ) { ?>
    <script>
      window.addEventListener("DOMContentLoaded",function(){jQuery(document).ready(function(e){e(".flex-control-nav").addClass("owl-productgallerygc"),e(".flex-control-nav li").addClass("item"),e(".owl-productgallerygc").owlCarousel({responsiveClass:!0,responsive:{0:{items:3},393:{items:4},480:{items:5},566:{items:6},769:{items:9},992:{items:4},1200:{items:5}},rtl:!0,loop:!1,rewind:!1,margin:10,dots:!1,nav:!0,stagePadding:23})})});
    </script>
<?php }
}

//Remove woocommerce sale flash
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 10 );

//Add stock condition in single product
add_action('woocommerce_single_product_summary', 'gajcommerce_instock_condition_single_prodcut', 6);
function gajcommerce_instock_condition_single_prodcut() {
  global $product;
  echo ($product->get_stock_status() == 'instock') ? '<div class="productavailabearea">موجود</div>' : '<div class="productnavailabearea">ناموجود</div>';
}

//Change position of excerpt for single product
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 7 );

//Change position of add to cart button for single product
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 10 );

//Remove basic price style from single product
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );

//Remove woocommerce rating from single product
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10 );

//Add custom gaj price style for single product
add_action( 'woocommerce_after_add_to_cart_quantity', 'gajcommerce_product_custom_price', 2 );
function gajcommerce_product_custom_price() {
  global $product;
  if (!$product-> is_type('variable')) {?>
  <div class="prodtails" style="<?php if($product->is_type( 'external' )) {echo 'border-top:none';} ?>">
    <div class="row">
      <div class="price-border-mobile d-block d-sm-none"></div>
      <?php $is_on_sale = $product->is_on_sale();
      if ( $is_on_sale ) { ?>
        <div class="col-12 col-sm-4 mt-1 mt-sm-0 mb-3 mb-sm-0">
          <div class="proprice">
            <span class="d-inline-block d-sm-none mobile">%<?php echo $percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 ); ?></span>
            <div class="d-none d-sm-block">قیمت:</div><span><?php echo number_format($product->get_regular_price()); echo '&nbsp;'; echo get_woocommerce_currency_symbol(); ?></span>
          </div>
        </div>
        <div class="col-4 d-none d-sm-block">
            <div class="promuchoff proprice">
              <img src="<?php echo get_template_directory_uri(); ?>/images/arooww.png" class="d-none d-sm-block">
              <div>تخفیف:</div>
              <span>%<?php echo $percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 ); ?></span>
            </div>
        </div>
        <div class="col-12 col-sm-4">
          <div class="proprice foryouprice">
            <div class="d-none d-sm-block">قیمت:</div><span><?php echo number_format($product->get_sale_price()); echo '&nbsp;'; echo get_woocommerce_currency_symbol(); ?></span>
          </div>
        </div>
      <?php } else {?>

        <div class="col-12">
          <div class="proprice foryouprice">
            <div class="d-none d-sm-block">قیمت:</div><span><?php echo $product->get_price_html(); ?></span>
          </div>
        </div>

      <?php } ?>
    </div>
  </div>
<?php } }

//Add add to cart button for mobile in single product
add_action( 'woocommerce_after_add_to_cart_button', 'gajcommerce_product_custom_price_mobile_button' , 2);
function gajcommerce_product_custom_price_mobile_button() {
  global $product;
  if (!$product->is_type('variable')) {?>
  <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt d-block d-sm-none mobileaddtocartgc"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>
<?php } else { ?>
  <button type="button" name="button" class="addtocartforvariablemobile mobileaddtocartgc d-block d-sm-none">انتخاب گزینه&zwnj;ها</button>
<?php } }

//Style for single product quantity
add_action( 'woocommerce_before_add_to_cart_quantity', 'gajcommerce_product_quaty' , 1);
function gajcommerce_product_quaty() {
  global $product;
  if ( $product->get_stock_quantity() ) {
    if ( $product->get_stock_quantity() > 1 and !$product->is_sold_individually()) {
      echo '<div class="proquty">تعداد';
    }
  } else {
    if ( !$product->is_sold_individually()) {
      echo '<div class="proquty">تعداد';
    }
  }
}
add_action( 'woocommerce_after_add_to_cart_quantity', 'gajcommerce_product_quaty_end' , 1);
function gajcommerce_product_quaty_end() {
  global $product;
  if ( $product->get_stock_quantity() ) {
    if ( $product->get_stock_quantity() > 1 and !$product->is_sold_individually()) {
      echo '</div>';
    }
  } else {
    if ( !$product->is_sold_individually()) {
      echo '</div>';
    }
  }
}

//Add plus and minus button for single product add to cart
  add_action( 'woocommerce_before_quantity_input_field', 'bbloomer_display_quantity_plus' );
  function bbloomer_display_quantity_plus() {
    if (!is_cart()) {
    global $product;
    if ( $product->get_stock_quantity() ) {
      if ( $product->get_stock_quantity() > 1 and !$product->is_sold_individually()) {
        echo '<button type="button" class="plus" ><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21"> <path fill="#9A9A9A" fill-rule="evenodd" d="M9 9V5.5a1.5 1.5 0 0 1 3 0V9h3.5a1.5 1.5 0 0 1 0 3H12v3.5a1.5 1.5 0 0 1-3 0V12H5.5a1.5 1.5 0 0 1 0-3H9zm1.5 12C4.701 21 0 16.299 0 10.5S4.701 0 10.5 0 21 4.701 21 10.5 16.299 21 10.5 21zm0-1a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19z"></path></svg></button>';
      }
    } else {
      if ( !$product->is_sold_individually()) {
        echo '<button type="button" class="plus" ><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21"> <path fill="#9A9A9A" fill-rule="evenodd" d="M9 9V5.5a1.5 1.5 0 0 1 3 0V9h3.5a1.5 1.5 0 0 1 0 3H12v3.5a1.5 1.5 0 0 1-3 0V12H5.5a1.5 1.5 0 0 1 0-3H9zm1.5 12C4.701 21 0 16.299 0 10.5S4.701 0 10.5 0 21 4.701 21 10.5 16.299 21 10.5 21zm0-1a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19z"></path></svg></button>';
      }
    }
  } else {
    echo '<button type="button" class="plus" ><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21"> <path fill="#9A9A9A" fill-rule="evenodd" d="M9 9V5.5a1.5 1.5 0 0 1 3 0V9h3.5a1.5 1.5 0 0 1 0 3H12v3.5a1.5 1.5 0 0 1-3 0V12H5.5a1.5 1.5 0 0 1 0-3H9zm1.5 12C4.701 21 0 16.299 0 10.5S4.701 0 10.5 0 21 4.701 21 10.5 16.299 21 10.5 21zm0-1a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19z"></path></svg></button>';
  }
}

  add_action( 'woocommerce_after_quantity_input_field', 'bbloomer_display_quantity_minus' );
  function bbloomer_display_quantity_minus() {
    if (!is_cart()) {
    global $product;
    if ( $product->get_stock_quantity() ) {
      if ( $product->get_stock_quantity() > 1 and !$product->is_sold_individually()) {
        echo '<button type="button" class="minus" ><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21"> <path fill="#9a9a9a" fill-rule="evenodd" d="M10.5 21C4.701 21 0 16.299 0 10.5S4.701 0 10.5 0 21 4.701 21 10.5 16.299 21 10.5 21zm0-1a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zm-5-11h10a1.5 1.5 0 0 1 0 3h-10a1.5 1.5 0 0 1 0-3z"></path></svg></button>';
      }
    } else {
      if ( !$product->is_sold_individually()) {
        echo '<button type="button" class="minus" ><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21"> <path fill="#9a9a9a" fill-rule="evenodd" d="M10.5 21C4.701 21 0 16.299 0 10.5S4.701 0 10.5 0 21 4.701 21 10.5 16.299 21 10.5 21zm0-1a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zm-5-11h10a1.5 1.5 0 0 1 0 3h-10a1.5 1.5 0 0 1 0-3z"></path></svg></button>';
      }
    }
  } else {
    echo '<button type="button" class="minus" ><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21"> <path fill="#9a9a9a" fill-rule="evenodd" d="M10.5 21C4.701 21 0 16.299 0 10.5S4.701 0 10.5 0 21 4.701 21 10.5 16.299 21 10.5 21zm0-1a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zm-5-11h10a1.5 1.5 0 0 1 0 3h-10a1.5 1.5 0 0 1 0-3z"></path></svg></button>';
  }
}

//Remove meta from single product
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );

//Remove add to wishlist main button
if( ! function_exists( 'yith_wcwl_selectively_hide_add_to_wishlist' ) ) {
	function yith_wcwl_selectively_hide_add_to_wishlist( $show ) {
		global $product;
		if ( $product instanceof WC_Product ) {
			$show = false;
		}
		return $show;
	}
	add_filter( 'yith_wcwl_show_add_to_wishlist', 'yith_wcwl_selectively_hide_add_to_wishlist' );
}

//Add infobox to single product page
add_action( 'woocommerce_single_product_summary', 'gajcommerce_product_info_box' , 90);
function gajcommerce_product_info_box() {
  $addinfopro=ot_get_option('addinfopro',false);
  if ($addinfopro!==false) { ?>
  	<div class="prosupportar d-none d-sm-flex">
  		<ul>
  			<?php foreach ($addinfopro as $key => $value) { ?>
  				<li><img src="<?php echo $value['proinfoimage'] ?>" alt=""><?php echo $value['title'] ?></li>
  		<?php	} ?>
  		</ul>
  	</div>
  <?php }
}

//Single product tags
add_action( 'woocommerce_after_single_product_summary', 'gajcommerce_product_tags_box' , 40);
function gajcommerce_product_tags_box() {
  global $product;
  if (!wc_get_product_tag_list( $product->get_id())) {return;} 
  echo '<div class="row"><div class="col-12"><div class="protags"><h3>برچسب‌های کالا</h3>';
  echo wc_get_product_tag_list( $product->get_id(), ', ' );
  echo '</div></div></div>';
}

//Remove variable products price range
add_filter( 'woocommerce_get_price_html', 'change_variable_products_price_display', 10, 2 );
function change_variable_products_price_display( $price, $product ) {

    // Only for variable products type
    if( ! $product->is_type('variable') ) return $price;

    $prices = $product->get_variation_prices( true );

    if ( empty( $prices['price'] ) )
    return apply_filters( 'woocommerce_variable_empty_price_html', '', $product );
    $min_price = current( $prices['price'] );
    $max_price = end( $prices['price'] );
    $prefix_html = '<span class="price-prefix">' . __('از ') . '</span>';
    $prefix = $min_price !== $max_price ? $prefix_html : ''; // HERE the prefix
    return apply_filters( 'woocommerce_variable_price_html', $prefix . wc_price( $min_price ) . $product->get_price_suffix(), $product );
}

//Gajcommerce ajax add to cart
function gc_addtocart_ajax_function() {
  if (ot_get_option('gc_addtocart_ajax','on') === 'on') {
    function ace_product_page_ajax_add_to_cart_js() {
    	global $post;
    	if( !is_object($post) )
            return;
        if( is_singular('product') ) {
    		$_product = wc_get_product( $post->ID );
        	if( $_product->is_type( 'external' ) ) {
    			return;
    		}
        ?>
      	<script type="text/javascript">
          jQuery(function(a){a("form.cart").on("submit",function(r){r.preventDefault();var t=a(this);t.block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var o=new FormData(this);o.append("add-to-cart",t.find("[name=add-to-cart]").val()),a.ajax({url:wc_add_to_cart_params.wc_ajax_url.toString().replace("%%endpoint%%","ace_add_to_cart"),data:o,type:"POST",processData:!1,contentType:!1,complete:function(r){if(r=r.responseJSON)if(r.error&&r.product_url)window.location=r.product_url;else if("yes"!==wc_add_to_cart_params.cart_redirect_after_add){var o=t.find(".single_add_to_cart_button");a(document.body).trigger("added_to_cart",[r.fragments,r.cart_hash,o]),a("form.cart .added_to_cart").remove(),a(".woocommerce-error, .woocommerce-message, .woocommerce-info").remove(),t.closest(".product").before(r.fragments.notices_html),t.unblock()}else window.location=wc_add_to_cart_params.cart_url}})})});
        </script><?php
      }
    }
    add_action( 'wp_footer', 'ace_product_page_ajax_add_to_cart_js' );

    /**
     * Add to cart handler.
     */
    function ace_ajax_add_to_cart_handler() {
    	WC_Form_Handler::add_to_cart_action();
    	WC_AJAX::get_refreshed_fragments();
    }
    add_action( 'wc_ajax_ace_add_to_cart', 'ace_ajax_add_to_cart_handler' );
    add_action( 'wc_ajax_nopriv_ace_add_to_cart', 'ace_ajax_add_to_cart_handler' );

    // Remove WC Core add to cart handler to prevent double-add
    remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );

    //Gajcommerce change cart total items ajax
    add_filter( 'woocommerce_add_to_cart_fragments', 'iconic_cart_count_fragments', 10, 1 );
    function iconic_cart_count_fragments( $fragments ) {

        $fragments['div.cartbox'] = '<div class="cartbox"><a href="' . wc_get_cart_url() . '"><i class="fas fa-shopping-cart"></i> | <figure>سبد خرید</figure> <span>' . WC()->cart->get_cart_contents_count() . '</span></a></div>';
        $fragments['span.sidesticktwonum'] = '<span class="sidesticktwonum">' . WC()->cart->get_cart_contents_count() . '</span>';
        $fragments['div.mobilecartnum'] = '<div class="circles mobilecartnum">' . WC()->cart->get_cart_contents_count() . '</div>';
        return $fragments;
    }

    add_filter( 'woocommerce_product_related_posts_query', 'alter_product_related_posts_query', 10, 3 );
    function alter_product_related_posts_query( $query, $product_id, $args ){
        global $wpdb;

        $query['join']  .= " INNER JOIN {$wpdb->postmeta} as pm ON p.ID = pm.post_id ";
        $query['where'] .= " AND pm.meta_key = '_stock_status' AND meta_value = 'instock' ";

        return $query;
    }
  } else {
    //Dequeue main js file and load js without ajax add to cart codes
    add_action('wp_print_scripts','gc_dequeue_main_js');
    function gc_dequeue_main_js() {
       wp_dequeue_script( 'jquery.mainjs' );
       wp_enqueue_script( 'jquery.mainjs.noajax', get_template_directory_uri().'/js/main_noajax.js',array (), '1.0', 'false');
    }
  }
}
add_action( 'after_setup_theme', 'gc_addtocart_ajax_function', 2 );

//Gajcommerce fix add to cart button for external products with ajax option on
add_action('wp_footer' , 'gc_disable_ajax_for_external_products');
function gc_disable_ajax_for_external_products() {
	global $product;
	if (is_product() && $product->is_type( 'external' ) && ot_get_option('gc_addtocart_ajax','on') === 'on') { ?>
	<script>jQuery( "button.single_add_to_cart_button" ).removeClass( "single_add_to_cart_button" )</script>
	<style>.product-type-external form.cart button.button{padding: 10px 30px 8px 32px;background: var(--maincolorgc, #8fcc1a)!important;border-radius: 25px;color: #fff;display: inline-block;outline: 0;border: none;transition: all .2s;margin-top: 40px;line-height: inherit;font-weight: 400;}</style>
	<?php }
}

//Chatzi notice
if (!is_plugin_active('chatzi/chatzi.php')) {
  function chatzi_daynaweb_notice() {
      $user_id = get_current_user_id();
      $url = get_home_url() . '/wp-admin/plugin-install.php?s=chatzi%20whatsapp&tab=search&type=term';
      if ( !get_user_meta( $user_id, 'chatzi_notice_dismissed' ) )
          echo '<div class="notice notice-warning" style="display: flex;justify-content: space-between;align-content: center;">
  <p><strong>افزونه رایگان چتزی</strong> را برای ارتباط راحت با مشتریان در واتس‌اپ نصب کنید!</p>
  <div style="display: inline-flex;align-items: center;">
  <a href="' . $url . '" style="text-decoration: none;background: #25d366;color: #fff;padding: 7px 12px;border-radius: 5px;font-weight: bold;box-shadow: 0px 5px 30px -7px #25d366;margin-left: 25px;">نصب افزونه</a>
  <a href="?chatzi-notice-dismissed" style="text-decoration: none;">پنهان کردن این پیام</a>
  </div>
  </div>';
  }
  add_action( 'admin_notices', 'chatzi_daynaweb_notice' );

  function my_plugin_notice_dismissed() {
      $user_id = get_current_user_id();
      if ( isset( $_GET['chatzi-notice-dismissed'] ) ) {
        add_user_meta( $user_id, 'chatzi_notice_dismissed', 'true', true );
        //delete_user_meta( $user_id, 'chatzi_notice_dismissed', 'true', true );
      }
  }
  add_action( 'admin_init', 'my_plugin_notice_dismissed' );
}

//Change translate of you may also like ...
add_filter( 'woocommerce_product_cross_sells_products_heading', 'translate_may_also_like' );

function translate_may_also_like() {
   return 'ممکن است به این محصولات نیز علاقمند باشید ...';
}

//Disable Woocommerce blocks styles
function ca_deregister_woocommerce_block_styles() {
  wp_deregister_style( 'wc-blocks-style' );
 wp_dequeue_style( 'wc-blocks-style' );
}
add_action( 'enqueue_block_assets', 'ca_deregister_woocommerce_block_styles' );

//Remove archive product page header hook
remove_action( 'woocommerce_shop_loop_header', 'woocommerce_product_taxonomy_archive_header' );

//Remove archive product page woocommerce pagination
remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination' );

// Set template of Cart & Checkout pages
function check_custom_cart_checkout_gc() {
  if ( ot_get_option('customcartcheckout','on') === 'on' ) {
    add_filter( 'page_template', 'gc_cart_checkout_template' );
  
    function gc_cart_checkout_template( $page_template ) {
      
      if ( is_cart() || is_checkout() ) {
          $page_template = get_template_directory() . '/inc/cart.php';
      }
      return $page_template;
    }
  }
}
add_action('after_setup_theme' , 'check_custom_cart_checkout_gc' , 3);

//Change cross sell position in cart page
remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display' );
add_action( 'woocommerce_after_cart_table' , 'woocommerce_cross_sell_display' );

//Custom wocoomerce butoon proceed to checkout in cart page
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout',20);
add_action( 'woocommerce_proceed_to_checkout', 'custom_button_proceed_to_checkout',20);
function custom_button_proceed_to_checkout() {
echo '<a href="'.esc_url(wc_get_checkout_url()).'" class="checkout-button button alt wc-forward">' .
__("اقدام به پرداخت", "woocommerce") . '<i class="fas fa-chevron-circle-left"></i>' . '</a>';
}