<?php




    /* Include main framework file */
    require_once(get_template_directory() . '/library/loader.php');
/*
function SearchFilter($query) {
  if ($query->is_search) {
    $query->set('post_type', 'pixad-autos');
  }
  return $query;
}
add_filter('pre_get_posts','SearchFilter');
*/


function template_chooser($template)   
{    
  global $wp_query;   
  $post_type = get_query_var('post_type');   
  if( $wp_query->is_search && $post_type == 'pixad-autos' )   
  {
    return locate_template('car-search.php');  
  }elseif($wp_query->is_search && $post_type == 'post'){
	  return locate_template('search.php'); 
  }   
  return $template;   
}
add_filter('template_include', 'template_chooser');  


add_action('check_admin_referer', 'logout_without_confirm', 10, 2);
function logout_without_confirm($action, $result)
{
    /**
     * Allow logout without confirmation
     */
    if ($action == "log-out" && !isset($_GET['_wpnonce'])) {
        $redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : 'url-you-want-to-redirect';
        $location = str_replace('&amp;', '&', wp_logout_url($redirect_to));
        header("Location: $location");
        die;
    }
}


add_action( 'autozone_header_start', 'autozone_header_cart', 10,1 );
function autozone_header_cart($autozone_header)
{

	if(class_exists('WooCommerce') && $autozone_header['header_minicart']){
		echo '<div class="header-navibox-4">';
		echo 	'<div class="header-cart">';
		echo		'<a href="' . wc_get_cart_url() . '"><i class="icon-handbag" aria-hidden="true"></i></a>';
		echo 		'<span class="header-cart-count">' . WC()->cart->cart_contents_count . '</span>';
		echo	  '</div>';
		echo	'</div>';
	}
}

function autozone_sort_auto_price($auto1,$auto2){
      $price1 = INF;
      $price2 = INF;
      $flag1 = 1;
      $flag2 = 1;
      if(!empty( get_post_meta( $auto1->ID, '_auto_price', true ))){
            $var1 = get_post_meta( $auto1->ID, '_auto_price', true );
            if((float)$var1 != 0) {
                  $price1 = (float) $var1;
            }elseif($var1 !== ''){
                  $price1 = INF;
                  $flag1 = 0;
            }
      }
      if(!empty( get_post_meta( $auto2->ID, '_auto_price', true ))){
            $var2 = get_post_meta( $auto2->ID, '_auto_price', true );
            if((float)$var2 != 0){
                  $price2 = (float) $var2;
                  }elseif($var2 !== ''){
                  $price2 = INF;
                  $flag2 = 0;
            }
      }
      if($flag1){
            if( !empty(get_post_meta( $auto1->ID, '_auto_sale_price', true ))){
                  $price1 =  (float) get_post_meta( $auto1->ID, '_auto_sale_price', true );
            }
      }
            if($flag2){
                  if( !empty(get_post_meta( $auto2->ID, '_auto_sale_price', true ))){
                              $price2 =  (float) get_post_meta( $auto2->ID, '_auto_sale_price', true );
                  }
            }

            $data = array_map( 'esc_attr', $_GET );
            if($data['order'] === '_auto_price-asc') $sort =1;
            elseif($data['order'] === '_auto_price-desc')$sort =-1;

            if($sort === 1){
                  if($price1 < $price2) return -1;
      elseif($price1 > $price2) return 1;
      else return 0;
            }elseif($sort === -1){
                  if($price1 < $price2) return 1;
      elseif($price1 > $price2) return -1;
      else return 0;
            }else return 0;
  }
  



$flag_activate = pixtheme_check_is_activated(); 
if ($flag_activate) {

  if (class_exists('PixthemeCustom')) {
    $pixtheme_plugin_dir = ABSPATH . 'wp-content/plugins/pixtheme-custom/';
    require_once($pixtheme_plugin_dir. '/plugin-update-checker/plugin-update-checker.php');

  $myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
    'http://assets.templines.com/plugins/theme/autozone/theme.json',
    __FILE__, //Full path to the main plugin file or functions.php.
    'autozone'
  );
    
  }

 // require 'plugin-update-checker/plugin-update-checker.php';


}else{

}




function autozone_wp_kses($string){
    $allowed_tags = array(
        'img' => array(
            'src' => array(),
            'alt' => array(),
            'width' => array(),
            'height' => array(),
            'class' => array(),
        ),
        'a' => array(
            'href' => array(),
            'title' => array(),
            'class' => array(),
        ),
        'span' => array(
            'class' => array(),
        ),
        'div' => array(
            'class' => array(),
            'id' => array(),
        ),
        'h1' => array(
            'class' => array(),
            'id' => array(),
        ),
        'h2' => array(
            'class' => array(),
            'id' => array(),
        ),
        'h3' => array(
            'class' => array(),
            'id' => array(),
        ),
        'h4' => array(
            'class' => array(),
            'id' => array(),
        ),
        'h5' => array(
            'class' => array(),
            'id' => array(),
        ),
        'h6' => array(
            'class' => array(),
            'id' => array(),
        ),
        'p' => array(
            'class' => array(),
            'id' => array(),
        ),
        'strong' => array(
            'class' => array(),
            'id' => array(),
        ),
        'i' => array(
            'class' => array(),
            'id' => array(),
        ),
        'del' => array(
            'class' => array(),
            'id' => array(),
        ),
        'ul' => array(
            'class' => array(),
            'id' => array(),
        ),
        'li' => array(
            'class' => array(),
            'id' => array(),
        ),
        'ol' => array(
            'class' => array(),
            'id' => array(),
        ),
        'input' => array(
            'class' => array(),
            'id' => array(),
            'type' => array(),
            'style' => array(),
            'name' => array(),
            'value' => array(),
        ),
        'br' => array(),
    );
    if (function_exists('wp_kses')) {
        return wp_kses($string, $allowed_tags);
    }
}



if (class_exists('WeDevs_Dokan')) {

//Dokan Add new menu
    function autozone_get_dashboard_nav($menus)
    {
        $custom_menus = [
            'add' => [
                'title' => __('Add Item', 'autozone'),
                'icon' => '<i class="fas fa-plus"></i>',
                'url' => dokan_get_navigation_url('add'),
                'pos' => 2,
            ],

        ];
        return array_merge($menus, $custom_menus);
    }

    add_filter('dokan_get_dashboard_nav', 'autozone_get_dashboard_nav');

    add_filter('dokan_query_var_filter', 'autozone_dokan_load_document_menu');
    function autozone_dokan_load_document_menu($query_vars)
    {
        $query_vars['add'] = 'add';
        return $query_vars;
    }

    add_action('dokan_load_custom_template', 'autozone_dokan_load_template');
    function autozone_dokan_load_template($query_vars)
    {
        if (isset($query_vars['add'])) {

            require_once get_template_directory() . '/dokan/add/add.php';
        }
    }

    function autozone_myacc_get_dashboard_nav($menus)
    {
        $custom_menus = [
            'myacc' => [
                'title' => __('My account', 'autozone'),
                'icon' => '<i class="fas fa-user"></i>',
                'url' => dokan_get_navigation_url('myacc'),
                'pos' => 1,
            ],

        ];
        return array_merge($menus, $custom_menus);
    }

    add_filter('dokan_get_dashboard_nav', 'autozone_myacc_get_dashboard_nav');

    add_filter('dokan_query_var_filter', 'autozone_myacc_dokan_load_document_menu');
    function autozone_myacc_dokan_load_document_menu($query_vars)
    {
        $query_vars['myacc'] = 'myacc';
        return $query_vars;
    }

    add_action('dokan_load_custom_template', 'autozone_myacc_dokan_load_template');
    function autozone_myacc_dokan_load_template($query_vars)
    {
        if (isset($query_vars['myacc'])) {

            if (is_user_logged_in()) {
                $author_ID = get_current_user_id();
                $user = get_user_by('ID', $author_ID);
                if (class_exists('WeDevs_Dokan')) {
                    $vendor = dokan()->vendor->get($author_ID);
                    if ($vendor->data->user_nicename != '') {
                        $header_btn_link = get_site_url() . '/members/' . $vendor->data->user_nicename;
                    } else {
                        $header_btn_link = get_site_url() . '/members/' . $user->user_login;
                    }
                } else {
                    $header_btn_link = get_site_url() . '/members/' . $user->user_login;
                }
                
                echo '<script>window.location.href = "' . $header_btn_link . '"</script>';
            }
        }
    }



    //Memb
    if(class_exists('MemberOrder')){
        function autozone_get_dashboard_nav_memb($menus)
        {
            $custom_menus = [
                'membership' => [
                    'title' => __('Membership', 'autozone'),
                    'icon' => '<i class="fas fa-gem"></i>',
                    'url' => dokan_get_navigation_url('membership'),
                    'pos' => 1,
                ],

            ];
            return array_merge($menus, $custom_menus);
        }
        add_filter('dokan_get_dashboard_nav', 'autozone_get_dashboard_nav_memb');
        add_filter('dokan_query_var_filter', 'autozone_dokan_load_document_menu_memb');
        function autozone_dokan_load_document_menu_memb($query_vars)
        {
            $query_vars['membership'] = 'membership';
            return $query_vars;
        }
        add_action('dokan_load_custom_template', 'autozone_dokan_load_template_memb');
        function autozone_dokan_load_template_memb($query_vars)
        {
            if (isset($query_vars['membership'])) {
                require_once get_template_directory() . '/dokan/membership/membership.php';
            }
        }
    }

    if(class_exists('Pixad_Booking_AUTO')){
        $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        if (strpos($url,'settings/store/') !== false) {
            add_action( 'wp_enqueue_scripts', 'autozone_deregister_scripts', 1000 );
            function autozone_deregister_scripts() {
                wp_deregister_script( 'pix-periodpicker-js' );
                wp_dequeue_script('pix-periodpicker-js');


                wp_deregister_script( 'pix-timepicker-js' );
                wp_dequeue_script('pix-timepicker-js');
            }
        }
    }
}
// Allow SVG
add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {

    global $wp_version;
    if ( $wp_version !== '4.7.1' ) {
       return $data;
    }
  
    $filetype = wp_check_filetype( $filename, $mimes );
  
    return [
        'ext'             => $filetype['ext'],
        'type'            => $filetype['type'],
        'proper_filename' => $data['proper_filename']
    ];
  
  }, 10, 4 );
  
  function cc_mime_types( $mimes ){
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
  }
  add_filter( 'upload_mimes', 'cc_mime_types' );
  
  function fix_svg() {
    echo '<style type="text/css">
          .attachment-266x266, .thumbnail img {
               width: 100% !important;
               height: auto !important;
          }
          </style>';
  }
  add_action( 'admin_head', 'fix_svg' );

  function enable_svg_upload( $upload_mimes ) {
    $upload_mimes['svg'] = 'image/svg+xml';
    $upload_mimes['svgz'] = 'image/svg+xml';
    return $upload_mimes;
}
add_filter( 'upload_mimes', 'enable_svg_upload', 10, 1 );

function custom_post_type() {
    $labels = array(
        'name'               => 'Add block',
        'singular_name'      => 'Add block',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New block',
        'edit_item'          => 'Edit block',
        'new_item'           => 'New block',
        'all_items'          => 'All blocks',
        'view_item'          => 'View Custom Post',
        'search_items'       => 'Search Custom Posts',
        'not_found'          => 'No custom posts found',
        'not_found_in_trash' => 'No custom posts found in Trash',
        'parent_item_colon'  => '',
        'menu_name'          => 'Static blocks'
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'custom-posts'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments')
    );

    register_post_type('custom_post', $args);
}

add_action('init', 'custom_post_type');

function register_checkout_menu() { 

	register_nav_menu('checkout_menu', 'Checkout menu');

}

add_action('after_setup_theme', 'register_checkout_menu');



add_action( 'wp_enqueue_scripts', 'misha_ajax_comments_scripts' );

function misha_ajax_comments_scripts() {
 
	wp_enqueue_script('jquery');
 
	wp_register_script( 'ajax_comment', get_stylesheet_directory_uri() . '/js/comments-ajax.js', array('jquery') );
 
	wp_localize_script( 'ajax_comment', 'misha_ajax_comment_params', array(
		'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php'
	) );
 
 	wp_enqueue_script( 'ajax_comment' );
}


add_action( 'wp_ajax_ajaxcomments', 'submit_ajax_comment' ); 
add_action( 'wp_ajax_nopriv_ajaxcomments', 'submit_ajax_comment' ); 

function misha_submit_ajax_comment(){

	$comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
	if ( is_wp_error( $comment ) ) {
		$error_data = intval( $comment->get_error_data() );
		if ( ! empty( $error_data ) ) {
			wp_die( '<p>' . $comment->get_error_message() . '</p>', __( 'Comment Submission Failure' ), array( 'response' => $error_data, 'back_link' => true ) );
		} else {
			wp_die( 'Unknown error' );
		}
	}
 
	$user = wp_get_current_user();
	do_action('set_comment_cookies', $comment, $user);
 

	$comment_depth = 1;
	$comment_parent = $comment->comment_parent;
	while( $comment_parent ){
		$comment_depth++;
		$parent_comment = get_comment( $comment_parent );
		$comment_parent = $parent_comment->comment_parent;
	}
 
 
	$GLOBALS['comment'] = $comment;
	$GLOBALS['comment_depth'] = $comment_depth;
	

	$comment_html = '<li ' . comment_class('', null, null, false ) . ' id="comment-' . get_comment_ID() . '">
		<article class="comment-body" id="div-comment-' . get_comment_ID() . '">
			<footer class="comment-meta">
				<div class="comment-author vcard">
					' . get_avatar( $comment, 100 ) . '
					<b class="fn">' . get_comment_author_link() . '</b> <span class="says">says:</span>
				</div>
				<div class="comment-metadata">
					<a href="' . esc_url( get_comment_link( $comment->comment_ID ) ) . '">' . sprintf('%1$s at %2$s', get_comment_date(),  get_comment_time() ) . '</a>';
					
					if( $edit_link = get_edit_comment_link() )
						$comment_html .= '<span class="edit-link"><a class="comment-edit-link" href="' . $edit_link . '">Edit</a></span>';
					
				$comment_html .= '</div>';
				if ( $comment->comment_approved == '0' )
					$comment_html .= '<p class="comment-awaiting-moderation">Your comment is awaiting moderation.</p>';

			$comment_html .= '</footer>
			<div class="comment-content">' . apply_filters( 'comment_text', get_comment_text( $comment ), $comment ) . '</div>
		</article>
	</li>';
	echo $comment_html;

	die();
	
}







function custom_meta_box() {
    add_meta_box(
        'custom_radio_meta_box',
        'Slider view',
        'render_custom_radio_meta_box',
        'pixad-autos', 
        'side',
        'low'
    );
}
add_action('add_meta_boxes', 'custom_meta_box');


function render_custom_radio_meta_box($post) {
    $value = get_post_meta($post->ID, '_custom_radio_meta_key', true);
    ?>
    <label>
        <input type="radio" name="custom_radio_field" value="carousel" <?php checked($value, 'carousel'); ?>>
        Carousel
    </label><br>
    <label>
        <input type="radio" name="custom_radio_field" value="grid" <?php checked($value, 'grid'); ?>>
        Grid
    </label><br>
    <label>
        <input type="radio" name="custom_radio_field" value="slider" <?php checked($value, 'slider'); ?>>
        Slider
    </label>
    <?php
}


function save_custom_radio_meta($post_id) {
    if (isset($_POST['custom_radio_field'])) {
        update_post_meta($post_id, '_custom_radio_meta_key', sanitize_text_field($_POST['custom_radio_field']));
    }
}
add_action('save_post', 'save_custom_radio_meta');


//*LOGIN FIX*//

add_action( 'wp_login_failed', 'tmtransport_front_end_login_fail' );function tmtransport_front_end_login_fail( $username ) {
    $referrer = $_SERVER['HTTP_REFERER'];    $referrer = str_replace('?notice=passwrong', '', $referrer);
    $referrer = str_replace('?notice=usernwrong', '', $referrer);    if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
        if(username_exists($username)){            if(class_exists('Youzify')){
                wp_redirect( $referrer . '?notice=passwrong' );            }
        } else {            if(class_exists('Youzify')) {
                wp_redirect($referrer . '?notice=usernwrong');            }
        }        exit;
    }}
add_action( 'woocommerce_login_form', 'tmtransport_my_account' );function tmtransport_my_account() {
    if(class_exists('Youzify')) {        if(isset($_GET['notice']) && $_GET['notice'] == 'passwrong') {
            $notice = '<span><strong>' . __("Error: ", "tm-transport") . '</strong>' . __('The password you entered is incorrect. ', 'tm-transport') . '</span>';        }elseif(isset($_GET['notice']) && $_GET['notice'] == 'usernwrong'){
            $notice = '<span><strong>' . __("Error: ", "tm-transport") . '</strong>' . __('The username is not registered on this site. If you are unsure of your username, try your email address instead. ', 'tm-transport'). '</span>';        }
        if(isset($_GET['notice']) && $_GET['notice'] == 'passwrong' || isset($_GET['notice']) && $_GET['notice'] == 'usernwrong'){ ?>            <script>
                jQuery(document).ready(function($) {                    jQuery('.woocommerce-notices-wrapper').html('<?php echo $notice;?>');
                });            </script>
        <?php }    }
}

//*Image size*//

function modify_image_srcset($sources) {
    unset($sources['320']);
    unset($sources['300']);
    unset($sources['200']);
  unset($sources['350']);
  unset($sources['600']);
  unset($sources['117']);
  unset($sources['850']);

    return $sources;
}

add_filter('wp_calculate_image_srcset', 'modify_image_srcset');