<?php
/**
 * noble_house_theme_web functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package noble_house_theme_web
 */

if ( ! defined( '_S_VERSION' ) ) {
	// Replace the version number of the theme on each release.
	define( '_S_VERSION', '1.0.0' );
}

/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
function noble_house_theme_web_setup() {
	/*
		* Make theme available for translation.
		* Translations can be filed in the /languages/ directory.
		* If you're building a theme based on noble_house_theme_web, use a find and replace
		* to change 'noble_house_theme_web' to the name of your theme in all the template files.
		*/
	load_theme_textdomain( 'noble_house_theme_web', get_template_directory() . '/languages' );

	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );

	/*
		* Let WordPress manage the document title.
		* By adding theme support, we declare that this theme does not use a
		* hard-coded <title> tag in the document head, and expect WordPress to
		* provide it for us.
		*/
	add_theme_support( 'title-tag' );

	/*
		* Enable support for Post Thumbnails on posts and pages.
		*
		* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		*/
	add_theme_support( 'post-thumbnails' );

	// This theme uses wp_nav_menu() in one location.
	register_nav_menus(
		array(
			'menu-1' => esc_html__( 'Primary', 'noble_house_theme_web' ),
		)
	);

	/*
		* Switch default core markup for search form, comment form, and comments
		* to output valid HTML5.
		*/
	add_theme_support(
		'html5',
		array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
			'style',
			'script',
		)
	);

	// Set up the WordPress core custom background feature.
	add_theme_support(
		'custom-background',
		apply_filters(
			'noble_house_theme_web_custom_background_args',
			array(
				'default-color' => 'ffffff',
				'default-image' => '',
			)
		)
	);

	// Add theme support for selective refresh for widgets.
	add_theme_support( 'customize-selective-refresh-widgets' );

	/**
	 * Add support for core custom logo.
	 *
	 * @link https://codex.wordpress.org/Theme_Logo
	 */
	add_theme_support(
		'custom-logo',
		array(
			'height'      => 250,
			'width'       => 250,
			'flex-width'  => true,
			'flex-height' => true,
		)
	);
}
add_action( 'after_setup_theme', 'noble_house_theme_web_setup' );

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function noble_house_theme_web_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'noble_house_theme_web_content_width', 640 );
}
add_action( 'after_setup_theme', 'noble_house_theme_web_content_width', 0 );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function noble_house_theme_web_widgets_init() {
	register_sidebar(
		array(
			'name'          => esc_html__( 'Col 3 Footer', 'noble_house_theme_web' ),
			'id'            => 'footer_col3',
			'description'   => esc_html__( 'Add widgets here.', 'noble_house_theme_web' ),
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		)
	);
	
        
	register_sidebar(
		array(
			'name'          => esc_html__( 'Socials', 'noble_house_theme_web' ),
			'id'            => 'socials_area',
			'description'   => esc_html__( 'Add widgets here.', 'noble_house_theme_web' ),
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		)
	);
        
	register_sidebar(
		array(
			'name'          => esc_html__( 'Contact Details', 'noble_house_theme_web' ),
			'id'            => 'contact_details',
			'description'   => esc_html__( 'Add widgets here.', 'noble_house_theme_web' ),
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		)
	);
}
add_action( 'widgets_init', 'noble_house_theme_web_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function noble_house_theme_web_scripts() {
	wp_enqueue_style( 'noble_house_theme_web-style', get_stylesheet_uri(), array(), _S_VERSION );
	wp_style_add_data( 'noble_house_theme_web-style', 'rtl', 'replace' );

	wp_enqueue_script( 'noble_house_theme_web-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );

	wp_enqueue_script( 'jquery-v2.1.4.min', get_template_directory_uri().'/js/jquery-v2.1.4.min.js', array(),  false , false); 
	wp_enqueue_script( 'slick.min', get_template_directory_uri().'/js/slick.min.js', array(),  false , true); 
	wp_enqueue_script( 'jquery.validate.min', get_stylesheet_directory_uri().'/js/jquery.validate.min.js', array(),  false , true);  //validate js
	wp_enqueue_script( 'jquery.magnific-popup.min', get_stylesheet_directory_uri().'/dist/jquery.magnific-popup.min.js', array(),  false , true); 
        wp_enqueue_script( 'font-awesome.min', get_stylesheet_directory_uri().'/js/font-awesome.min.js', array(),  false , true); 
	wp_enqueue_script('custom_js', get_stylesheet_directory_uri().'/js/custom_js.js', array(),  false , true);
	
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'noble_house_theme_web_scripts' );

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';

/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/inc/template-functions.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';

/**
 * Load Jetpack compatibility file.
 */
if ( defined( 'JETPACK__VERSION' ) ) {
	require get_template_directory() . '/inc/jetpack.php';
}


//================Image size============================//

//add_image_size( 'category_size', 400, 400, true );
// add_image_size( 'gallery_full', 1200, 900, true );

add_image_size( 'gallery_size', 1000, 670, true );


if(!function_exists('mit_thumbnail_upscale')) {
function mit_thumbnail_upscale( $default, $orig_w, $orig_h, $new_w, $new_h, $crop ){

    if ( !$crop ) return null; // let the wordpress default function handle this

    $aspect_ratio = $orig_w / $orig_h;
    $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);

    $crop_w = round($new_w / $size_ratio);
    $crop_h = round($new_h / $size_ratio);

    $s_x = floor( ($orig_w - $crop_w) / 2 );
    $s_y = floor( ($orig_h - $crop_h) / 2 );

    return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}
}
add_filter( 'image_resize_dimensions', 'mit_thumbnail_upscale', 10, 6 );

//================Image size============================//


//================widgets folder============================//
function wbexample_add_widget_folders( $folders ){
    $folders[] = get_template_directory() . '/widgets/';
    return $folders;
}
add_action('siteorigin_widgets_widget_folders', 'wbexample_add_widget_folders');
function widgets_tab($tabs) {
    $tabs[] = array(
        'title' => __('NH widgets', 'mytheme'),
        'filter' => array(
            'groups' => array('nh')
        )
    );
    return $tabs;
}

add_filter('siteorigin_panels_widget_dialog_tabs', 'widgets_tab', 20);
//================widgets folder============================//


// remove wp version number from scripts and styles
function remove_css_js_version( $src ) {
    if( strpos( $src, '?ver=' ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
add_filter( 'style_loader_src', 'remove_css_js_version', 9999 );
add_filter( 'script_loader_src', 'remove_css_js_version', 9999 );



//page builder rows custom class
function custom_row_style_fields($fields) {
  $fields['custom_container'] = array(
      'name'        => __('Container Type', 'siteorigin-panels'),
      'type'        => 'select',
	  'default' => 'middle_container',
	  'options' => array(
		'large_container' => __( 'Large Container', 'widget-form-fields-text-domain' ),
			'middle_container' => __( 'Middle Container', 'widget-form-fields-text-domain' ),
			'full_container' => __( 'Full Container', 'widget-form-fields-text-domain' ),
			'small_container' => __( 'Small Container', 'widget-form-fields-text-domain' ),
			
		),
      'group'       => 'design',
      'description' => __('Select a custom container', 'siteorigin-panels'),
      'priority'    => 8,
  );
  $fields['order_cells'] = array(
      'name'        => __('Order of columns (if 2 columns  -- for mobile)', 'siteorigin-panels'),
      'type'        => 'select',
	  'default' => 'default_order',
	  'options' => array(
			'default_order' => __( 'Defalt Order', 'widget-form-fields-text-domain' ),
			'reverse_order' => __( 'Reverse Columns', 'widget-form-fields-text-domain' ),
		),
      'group'       => 'design',
      'description' => __('Select columns order', 'siteorigin-panels'),
      'priority'    => 9,
  );
  return $fields;
}


add_filter( 'siteorigin_panels_row_style_fields', 'custom_row_style_fields' );
function custom_row_style_attributes( $attributes, $args ) {
    if( !empty( $args['custom_container'] ) ) {
        array_push($attributes['class'], $args['custom_container']);
    }
	 if( !empty( $args['order_cells'] ) ) {
        array_push($attributes['class'], $args['order_cells']);
    }
	
    return $attributes;
}

add_filter('siteorigin_panels_row_style_attributes', 'custom_row_style_attributes', 10, 2);
//page builder rows custom class



//Appearance customizer
function nh_customizer( $wp_customize ) {
    $wp_customize->add_section(
        'nh_section',
        array(
            'title' => 'NH Utils',
            'description' => 'NH settings.',
            'priority' => 35,
        )
    );
	
	$wp_customize->add_setting( 'logo_header' );
	$wp_customize->add_control(
		new WP_Customize_Image_Control(
			$wp_customize,
			'logo_header',
			array(
				'label' => 'Logo Header',
				'section' => 'nh_section',
				'settings' => 'logo_header'
			)
		)
	);
	$wp_customize->add_setting( 'logo_footer' );
	$wp_customize->add_control(
		new WP_Customize_Image_Control(
			$wp_customize,
			'logo_footer',
			array(
				'label' => 'Logo Footer',
				'section' => 'nh_section',
				'settings' => 'logo_footer'
			)
		)
	);
	$wp_customize->add_setting( 'replacer_top_image' );
	$wp_customize->add_control(
		new WP_Customize_Image_Control(
			$wp_customize,
			'replacer_top_image',
			array(
				'label' => 'Replacer Top image',
				'section' => 'nh_section',
				'settings' => 'replacer_top_image'
			)
		)
	);

	
}
add_action( 'customize_register', 'nh_customizer' );

add_theme_support( 'admin-bar', array( 'callback' => '__return_false' ) );

///add custom post types
function create_post_type() {

 
  register_post_type( 'layouts_cpt',
    array(
      'labels' => array(
        'name' => __( 'Layouts' ),
        'singular_name' => __( 'Layout Item' )
      ),
      'public' => true,
      'exclude_from_search' => true,
      'has_archive' => false,
		'taxonomies' => array(''),
        'supports' => array('title','editor','thumbnail','page-attributes'),
		'show_in_menu'        => TRUE,
		'menu_position'       => 5,
		'rewrite' => array('slug' => "layouts"),
		'publicly_queryable'  => false

    )
  );

}
add_action( 'init', 'create_post_type' );



function get_excerpt_trim($num_words='20', $more='...'){
    $excerpt = get_the_excerpt();
    $excerpt = wp_trim_words( $excerpt, $num_words , $more );
    return $excerpt;
}


function load_template_part($template_name, $part_name=null) {
    ob_start();
    get_template_part($template_name, $part_name);
    $var = ob_get_contents();
    ob_end_clean();
    return $var;
}



//woo functions

function mytheme_add_woocommerce_support() {
	add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' );

//woocommerce light box gallery

add_action( 'after_setup_theme', 'mystile1_setup' );

function mystile1_setup() {
	add_theme_support( 'wc-product-gallery-zoom' );
	add_theme_support( 'wc-product-gallery-lightbox' );
	add_theme_support( 'wc-product-gallery-slider' );
}
//woocommerce light box gallery

// remove button add to card
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 20);




//custom plus minus quantity input
function jh_add_script_to_footer(){
    if( ! is_admin() ) { ?>
    <script>
  
jQuery(document).ready(function($){
$(document).on('click', '.plus', function(e) { // replace '.quantity' with document (without single quote)
    $input = $(this).prev('input.qty');
    var val = parseInt($input.val());
    var step = $input.attr('step');
    step = 'undefined' !== typeof(step) ? parseInt(step) : 1;
    $input.val( val + step ).change();
	//$('.actions button[name="update_cart"]').trigger('click');
});
$(document).on('click', '.minus',  // replace '.quantity' with document (without single quote)
    function(e) {
    $input = $(this).next('input.qty');
    var val = parseInt($input.val());
    var step = $input.attr('step');
    step = 'undefined' !== typeof(step) ? parseInt(step) : 1;
    if (val > 1) {
        $input.val( val - step ).change();
		//$('.actions button[name="update_cart"]').trigger('click');
    }
	
});

});
</script>
<?php
    }
}
add_action( 'wp_footer', 'jh_add_script_to_footer' );
//custom plus minus quantity input

//remove select2
add_action( 'wp_enqueue_scripts', 'mgt_dequeue_stylesandscripts', 100 );

function mgt_dequeue_stylesandscripts() {
    if ( class_exists( 'woocommerce' ) ) {
        wp_dequeue_style( 'select2' );
        wp_deregister_style( 'select2' );
        wp_dequeue_style( 'selectWoo' );
        wp_deregister_style( 'selectWoo' );

        wp_dequeue_script( 'select2');
        wp_deregister_script('select2');
        wp_dequeue_script( 'selectWoo');
        wp_deregister_script('selectWoo');

    } 
} 
//remove select2

//woocommerce
 add_filter( 'get_the_archive_title', function ($title) {  
		if(is_woocommerce() || is_cart() ||  is_shop() || is_product() || is_cart() || is_checkout() || is_account_page()){
			if(is_shop()){
				$title = 'Shop';
			}elseif(is_product()){
				$title = get_the_title();
			}elseif(is_product_category()){
				$title = single_cat_title( '', false );
			}elseif(is_cart()){
				$title = 'Cart';
			}elseif(is_checkout()){
				$title = 'Checkout';
			}elseif(is_account_page()){
				$title = 'My Account';
			}else{
				$title = get_the_title();
			}
		}else{
			if ( is_category() ) {    
				$title = single_cat_title( '', false );    
			} elseif ( is_tag() ) {    
				$title = single_tag_title( '', false );    
			} elseif ( is_author() ) {    
				$title = '<span class="vcard">' . get_the_author() . '</span>' ;    
			} elseif ( is_tax() ) { //for custom post types
				$title = sprintf( __( '%1$s' ), single_term_title( '', false ) );
			} elseif (is_post_type_archive()) {
				$title = post_type_archive_title( '', false );
			}elseif (is_404()) {
				$title = 'Page not found';
			}elseif (is_search()) {
				$title = 'Search';
			}
		}
        
        return $title;    
    });

add_action( 'woocommerce_before_single_product', 'tm_child_move_rel_prod_below_wc_tabs', 20 );

function tm_child_move_rel_prod_below_wc_tabs() {
	remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
   // add_action( 'woocommerce_after_single_product',    'woocommerce_output_related_products', 20 );   //uncomment if related products needed on single product page
}



//remove woocommerce tabs
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );

function woo_remove_product_tabs( $tabs ) {
    unset( $tabs['description'] );          // Remove the description tab
   // unset( $tabs['reviews'] );          // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab
    return $tabs;
}


//remove woocommerce tabs
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
add_action( 'woocommerce_after_single_product', 'woocommerce_output_product_data_tabs', 60 );

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );

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', 15 );


//move position of coupon code on cart page 
/*
add_action( 'woocommerce_cart_collaterals', 'bbloomer_display_coupon_form_below_proceed_checkout', 25 );
 
function bbloomer_display_coupon_form_below_proceed_checkout() {
   ?> 
      <form class="woocommerce-coupon-form" action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post">
         <?php if ( wc_coupons_enabled() ) { 
			echo '<h2 class="coupon_code_title">Have a promo code?</h2>';
		 ?>
            <div class="coupon under-proceed">
               <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" style="width: 100%" /> 
               <button type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>" style="width: 100%"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
            </div>
         <?php } ?>
      </form>
   <?php
}
 * 
 */






/**
 * Add [add_to_cart_form] shortcode that display a single product add to cart form
 * Supports id and sku attributes [add_to_cart_form id=99] or [add_to_cart_form sku=123ABC]
 * Essentially a duplicate of the [product_page]
 * but replacing wc_get_template_part( 'content', 'single-product' ); with woocommerce_template_single_add_to_cart()
 *
 * @param array $atts Attributes.
 * @return string
 */
function kia_add_to_cart_form_shortcode( $atts ) {
		if ( empty( $atts ) ) {
			return '';
		}

		if ( ! isset( $atts['id'] ) && ! isset( $atts['sku'] ) ) {
			return '';
		}

		$args = array(
			'posts_per_page'      => 1,
			'post_type'           => 'product',
			'post_status'         => 'publish',
			'ignore_sticky_posts' => 1,
			'no_found_rows'       => 1,
		);

		if ( isset( $atts['sku'] ) ) {
			$args['meta_query'][] = array(
				'key'     => '_sku',
				'value'   => sanitize_text_field( $atts['sku'] ),
				'compare' => '=',
			);

			$args['post_type'] = array( 'product', 'product_variation' );
		}

		if ( isset( $atts['id'] ) ) {
			$args['p'] = absint( $atts['id'] );
		}

		$single_product = new WP_Query( $args );

		$preselected_id = '0';

		// Check if sku is a variation.
		if ( isset( $atts['sku'] ) && $single_product->have_posts() && 'product_variation' === $single_product->post->post_type ) {

			$variation = new WC_Product_Variation( $single_product->post->ID );
			$attributes = $variation->get_attributes();

			// Set preselected id to be used by JS to provide context.
			$preselected_id = $single_product->post->ID;

			// Get the parent product object.
			$args = array(
				'posts_per_page'      => 1,
				'post_type'           => 'product',
				'post_status'         => 'publish',
				'ignore_sticky_posts' => 1,
				'no_found_rows'       => 1,
				'p'                   => $single_product->post->post_parent,
			);

			$single_product = new WP_Query( $args );
		?>
			<script type="text/javascript">
				jQuery( document ).ready( function( $ ) {
					var $variations_form = $( '[data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>"]' ).find( 'form.variations_form' );

					<?php foreach ( $attributes as $attr => $value ) { ?>
						$variations_form.find( 'select[name="<?php echo esc_attr( $attr ); ?>"]' ).val( '<?php echo esc_js( $value ); ?>' );
					<?php } ?>
				});
			</script>
		<?php
		}

		// For "is_single" to always make load comments_template() for reviews.
		$single_product->is_single = true;

		ob_start();

		global $wp_query;

		// Backup query object so following loops think this is a product page.
		$previous_wp_query = $wp_query;
		// @codingStandardsIgnoreStart
		$wp_query          = $single_product;
		// @codingStandardsIgnoreEnd

		wp_enqueue_script( 'wc-single-product' );

		while ( $single_product->have_posts() ) {
			$single_product->the_post()
			?>
			<div class="single-product" data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>">
				<?php woocommerce_template_single_add_to_cart(); ?>
			</div>
			<?php
		}

		// Restore $previous_wp_query and reset post data.
		// @codingStandardsIgnoreStart
		$wp_query = $previous_wp_query;
		// @codingStandardsIgnoreEnd
		wp_reset_postdata();

		return '<div class="woocommerce bx_bottom">' . ob_get_clean() . '</div>';
}

add_shortcode( 'add_to_cart_form', 'kia_add_to_cart_form_shortcode' );


/**
 * Changes the redirect URL for the Return To Shop button in the cart.
 *
 * @return string
 */
function wc_empty_cart_redirect_url() {
	return site_url();
}
add_filter( 'woocommerce_return_to_shop_redirect', 'wc_empty_cart_redirect_url' );
        
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     $fields['order']['order_comments']['placeholder'] = 'Enter your block captain or any other important information';
     $fields['order']['order_comments']['label'] = '';
     return $fields;
}
add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );

