<?php
@ini_set('upload_max_size', '64M');
@ini_set('post_max_size', '64M');
@ini_set('max_execution_time', '300');

//Get Zones 
function get_zones($post_ID = 157) {
    if (get_field('zones_commerciaux', $post_ID)):
        $i = 0;
        while (has_sub_field('zones_commerciaux', $post_ID)) :
            if (get_sub_field('list_zones', $post_ID)):
                $list_zone = array();
                while (has_sub_field('list_zones', $post_ID)) :
                    $list_zone[] = get_sub_field('num_zone');
                endwhile;
            endif;
            $allZones['zone' . $i] = $list_zone;
            $i++;
        endwhile;
    endif;
    return json_encode($allZones);
}

function nap_enqueue_scripts() {
    // Enqueue jQuery UI and autocomplete
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-ui-autocomplete');
}

add_action('wp_enqueue_scripts', 'nap_enqueue_scripts');

//Dequeue CSS
function nap_dequeue_unnecessary_css() {
    wp_dequeue_style('additional-parent-style');
    wp_deregister_style('additional-parent-style');
    wp_dequeue_style('twentyseventeen-fonts');
    wp_dequeue_style('nf-display-style');
}

add_action('wp_enqueue_scripts', 'nap_dequeue_unnecessary_css', 100);

//Dequeue JavaScripts
function nap_dequeue_unnecessary_scripts() {
    wp_dequeue_script('twentyseventeen-global');
    wp_deregister_script('twentyseventeen-global');
    wp_dequeue_script('jquery-scrollto');
    wp_deregister_script('jquery-scrollto');
    wp_dequeue_script('twentyseventeen-skip-link-focus-fix');
    wp_deregister_script('twentyseventeen-skip-link-focus-fix');
    wp_dequeue_script('twentyseventeen-navigation');
    wp_deregister_script('twentyseventeen-navigation');

    //MS : 2017-07-17
    wp_register_script('getZones', home_url('wp-content/themes/nap/assets') . '/js/map.js');
    $listZones = array('listZones' => get_zones(157));

    wp_localize_script('getZones', 'zonesL', $listZones);
    //  wp_localize_script( 'listZones', 'object_name', $listZones );
    wp_enqueue_script('getZones');
    //END MS : 2017-07-17
}

add_action('wp_print_scripts', 'nap_dequeue_unnecessary_scripts');

//Display SVG
function nap_wpc_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}

add_filter('upload_mimes', 'nap_wpc_mime_types');

add_filter('redirect_canonical', 'nap_custom_disable_redirect_canonical');

function nap_custom_disable_redirect_canonical($redirect_url) {
    if (is_paged() && is_singular())
        $redirect_url = false;
    return $redirect_url;
}

function nap_change_wp_search_size($query) {
    if ($query->is_search)
        $query->query_vars['posts_per_page'] = 200;

    return $query;
}

add_filter('pre_get_posts', 'nap_change_wp_search_size');

//Custom logo 
function nap_custom_loginlogo() {
    echo '<style type="text/css">
    h1 a {background-image: url(' . home_url('wp-content/themes/nap/assets/images/logo.svg') . ') !important;width:102px !important;background-size:100px !important;height:52px !important;background: #05162b;
    opacity: 0.9; }
    </style>';
}

add_action('login_head', 'nap_custom_loginlogo');

// Move Yoast to bottom
function nap_yoasttobottom() {
    return 'low';
}

add_filter('wpseo_metabox_prio', 'nap_yoasttobottom');

add_filter('admin_footer_text', '__return_empty_string', 11);
add_filter('update_footer', '__return_empty_string', 11);

//===============================================================================


function nap_get_content($postID) {
    $content_post = get_post($postID);
    $content = $content_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);
    return $content;
}

add_action('init', 'nap_create_post_type');

function nap_create_post_type() {
    register_post_type('fiche_technique', array(
        'labels' => array(
            'name' => __('Fiches Techniques'),
            'singular_name' => __('Fiche Technique')
        ),
        'public' => true
            )
    );
}

function nap_post_type_listing($post_type) {
    $select = array();
    $posts = get_posts(
            array(
                'post_type' => $post_type,
                'numberposts' => -1
            )
    );
    if (!$posts)
        return;


    foreach ($posts as $p) {

        $select[$p->ID] = $p->post_title;
    }

    return $select;
}

add_action('woocommerce_product_after_variable_attributes', 'nap_variation_settings_fields', 10, 3);

function nap_variation_settings_fields($loop, $variation_data, $variation) {



    // Gencode
    woocommerce_wp_text_input(
            array(
                'id' => 'var_gencod_' . $variation->ID,
                'label' => __('Gencod(EAN13)', 'woocommerce'),
                'value' => get_post_meta($variation->ID, '_var_gencod', true),
                'custom_attributes' => array(
                    'step' => 'any',
                    'min' => '0'
                )
            )
    );

    // ITF 14
    woocommerce_wp_text_input(
            array(
                'id' => 'var_itf14_' . $variation->ID,
                'label' => __('ITF 14', 'woocommerce'),
                'value' => get_post_meta($variation->ID, '_var_itf14', true),
                'custom_attributes' => array(
                    'step' => 'any',
                    'min' => '0'
                )
            )
    );

    $option = nap_post_type_listing('fiche_technique');
    woocommerce_wp_text_input(
            array(
                'id' => 'fiche_var_auto_' . $variation->ID,
                'name' => 'fiche_var_auto_' . $variation->ID,
                'value' => get_post_meta($variation->ID, 'fiche_var_auto', true),
                'label' => __('Fiche technique', 'woocommerce'),
            )
    );
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function() {

            var posts = <?php echo json_encode($option); ?>;
            var data = [];
            jQuery.each(posts, function(index, value) {

                data.push({'label': value, 'value': index});
            });
            jQuery('input[name="fiche_var_auto_<?php echo $variation->ID ?>"]').click(function() {
                jQuery(this).val('');
            });
            jQuery('input[name="fiche_var_auto_<?php echo $variation->ID ?>"]').autocomplete({
                source: data,
                minLength: 1,
                select: function(event, ui) {
                    event.preventDefault();
                    jQuery(this).val(ui.item.label);
                    jQuery("#_var_fiche_<?php echo $variation->ID ?>").val(ui.item.value);
                }
            });
        });
    </script>
    <?php
    woocommerce_wp_hidden_input(
            array(
                'id' => '_var_fiche_' . $variation->ID,
                'label' => __('Fiche technique', 'woocommerce'),
                'value' => get_post_meta($variation->ID, '_var_fiche', true),
                'name' => '_var_fiche_' . $variation->ID,
            )
    );
}

// Save Variation Settings
add_action('woocommerce_save_product_variation', 'nap_save_variation_settings_fields', 10, 2);

function nap_save_variation_settings_fields($variation_id) {

    // Gencode
    $var_gencod = $_POST['var_gencod_' . $variation_id];
    if (!empty($var_gencod)) {
        update_post_meta($variation_id, '_var_gencod', esc_attr($var_gencod));
    }
    // ITF 14
    $var_itf14 = $_POST['var_itf14_' . $variation_id];
    if (!empty($var_itf14)) {
        update_post_meta($variation_id, '_var_itf14', esc_attr($var_itf14));
    }

    // Select fiches techniques
    $var_fiche = $_POST['_var_fiche_' . $variation_id];
    if (!empty($var_fiche)) {
        update_post_meta($variation_id, '_var_fiche', esc_attr($var_fiche));
    }


    $select_fiche = $_POST['fiche_var_auto_' . $variation_id];
    if (!empty($select_fiche)) {
        update_post_meta($variation_id, 'fiche_var_auto', esc_attr($select_fiche));
    }
}

function nap_load_variation_settings_fields($variations_id) {

    // duplicate the line for each field
    $variations['var_code'] = get_post_meta($variations_id, '_var_code', true);
    $variations['var_gencod'] = get_post_meta($variations_id, '_var_gencod', true);
    $variations['var_itf14'] = get_post_meta($variations_id, '_var_itf14', true);
    $variations['var_fiche'] = get_post_meta($variations_id, '_var_fiche', true);

    return $variations;
}

function nap_category_image($catID) {
    $thumbnail_id = get_woocommerce_term_meta($catID, 'thumbnail_id', true);
    $image = wp_get_attachment_image_src($thumbnail_id, 'large');
    return $image[0];
}

function nap_attachment_image($pageID) {
    $thumb = wp_get_attachment_image_src(get_post_thumbnail_id($pageID), 'large');
    $url = $thumb['0'];
    return $url;
}

function nap_menu() {

    $menu = "";
    $taxonomy = 'product_cat';
    $orderby = 'id';
    $show_count = 0;
    $pad_counts = 0;
    $hierarchical = 1;
    $title = '';
    $empty = 0;

    $args = array(
        'taxonomy' => $taxonomy,
        'orderby' => $orderby,
        'show_count' => $show_count,
        'pad_counts' => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li' => $title,
        'hide_empty' => $empty
    );
    $all_categories = get_categories($args);
    foreach ($all_categories as $cat) {
        if ($cat->category_parent == 0) {
            $category_id = $cat->term_id;
            $menu.= '<li data-page = "' . $category_id . '" data-img = "' . nap_category_image($category_id) . '"><a href="' . get_term_link($cat->slug, 'product_cat') . '">' . $cat->name . '</a>';

            $args2 = array(
                'taxonomy' => $taxonomy,
                'child_of' => 0,
                'parent' => $category_id,
                'orderby' => 'title',
                'show_count' => $show_count,
                'pad_counts' => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li' => $title,
                'hide_empty' => 1
            );
            $sub_cats = get_categories($args2);
            $menu.= ' <ul class = "subcat" data-page = "' . $category_id . '">';
            if ($sub_cats) {
                $class = '';
                foreach ($sub_cats as $key => $sub_category) {

                    if ($key == 0)
                        $calss = 'active';
                    else
                        $calss = '';
                    $menu.= '<li data-cover = "' . nap_category_image($sub_category->term_id) . '"><a class="' . $calss . '" href="#cat' . $sub_category->term_id . '">' . $sub_category->name . '</a></li>';
                }
            }

            $menu.= '</ul></li>';
        }
    }

    return $menu;
}

function nap_variation_url($variationID) {

    $variable_product = wc_get_product($variationID);

    $couleur = $variable_product->get_attribute('couleur');
    $color_url = get_term_by('slug', $couleur, 'pa_couleur');
    $format = $variable_product->get_attribute('format');
    $format_url = get_term_by('slug', $format, 'pa_format');
    $url = '?attribute_couleur=' . $color_url->slug . '&attribute_format=' . $format_url->slug . '&variation_id=' . $variationID;
    return preg_replace('/\s+/', '', $url);
}

function nap_variation_color($variationID) {
    $variable_product = wc_get_product($variationID);

    $term = get_term_by('name', $variable_product->get_attribute('couleur'), 'pa_couleur');
    $termID = $term->term_id;
    $color = get_field('couleurs', 'pa_couleur_' . $termID);

    return $color;
}

function nap_color_attribute($name) {
    $term = get_term_by('slug', $name, 'pa_couleur');
    $termID = $term->term_id;
    $color = get_field('couleurs', 'pa_couleur_' . $termID);

    return $color;
}

function nap_icon_format($name) {
    $icons = array();
    $term = get_term_by('slug', $name, 'pa_format');
    $termID = $term->term_id;
    $active = get_field('format_icone_active', 'pa_format_' . $termID);
    $inactive = get_field('format_icone_inactive', 'pa_format_' . $termID);
    $iconHeight = get_field('hauteur_icone', 'pa_format_' . $termID);
    $iconWidth = get_field('largeur_icone', 'pa_format_' . $termID);

    $icons['active'] = $active;
    $icons['inactive'] = $inactive;
    $icons['height'] = $iconHeight;
    $icons['width'] = $iconWidth;
    return $icons;
}

function nap_distinct_color_variations($variations) {
    $var_colors = array();
    foreach ($variations as $variation) :
        $variation_ID = $variation['variation_id'];
        $color = nap_variation_color($variation_ID);
        if (!in_array($color, $var_colors)):
            $var_colors[$variation_ID] = $color;
        endif;
    endforeach;
    return $var_colors;
}

function nap_variation_format($variationID) {
    $variable_product = wc_get_product($variationID);
    return $variable_product->get_attribute('format');
}

function nap_distinct_format_variations($variations) {
    $var_format = array();
    foreach ($variations as $variation) :
        $variation_ID = $variation['variation_id'];
        $format_name = nap_variation_format($variation_ID);
        $term = get_term_by('name', $format_name, 'pa_format');
        $termID = $term->term_id;
        if (!in_array($termID, $var_format)):
            $var_format[$termID] = $format_name;
        endif;
    endforeach;
    // print_r($var_format);
    return $var_format;
}

function nap_filter_attribute($id, $args, $options, $list_attr, $search) {
    if(isset($search['pa_format']) && $search['pa_format']!=''){
        $list_format=explode(",", $search['pa_format']);
    }
    if(isset($search['pa_couleur']) && $search['pa_couleur']!=''){
        $list_couleur=explode(",", $search['pa_couleur']);
    }
    if(isset($search['pa_matiere']) && $search['pa_matiere']!=''){
        $list_matiere=explode(",", $search['pa_matiere']);
    }
    if(isset($search['pa_univers']) && $search['pa_univers']!=''){
        $list_univers=explode(",", $search['pa_univers']);
    }
   if(
        ( ($list_couleur && in_array($list_attr['pa_couleur'],$list_couleur)) || empty($list_couleur) ) &&
        ( ($list_format && in_array($list_attr['pa_format'],$list_format)) || empty($list_format) ) &&
        ( ($list_univers && in_array($list_attr['pa_univers'],$list_univers)) || empty($list_univers) ) &&
        ( ($list_matiere && in_array($list_attr['pa_matiere'],$list_matiere)) || empty($list_matiere) ) 
    )
   {
      echo nap_get_item($id, $args, 'catalogue', $options);
   }
}

function nap_get_item($post_ID, $args = null, $current_page = '', $options = null, $search = null) {

    $link = $image = $size = '';
    if (isset($options)) {
        if ($options['dwnldLink']) {
            $link = ' <a class = "circle-btn download-btn hidden-elem" download href="' . $options['dwnldLink'] . '"></a>';
        }

        if ($options['image']) {
            $image = $options['image'];
        }

        if ($options['size']) {
            $size = $options['size'];
        }

        if ($options['title']) {
            $title_item = $options['title'];
        } else {
            $title_item = get_the_title($post_ID);
        }
    }

    /* if (isset($search['pa_couleur']) && $search['pa_couleur'] != '') {
      $colors_value = get_the_terms($post_ID, 'pa_couleur');
      $filter = "hidden";
      if (is_array($colors_value)) {
      foreach ($colors_value as $key => $value) {
      $code = nap_color_attribute($value->slug);

      if ($code != '' && stristr($search['pa_couleur'], $code)) {
      $filter = "selected";
      }
      }
      }
      }
      /*$attributes = array('Univers' => 'pa_univers', 'Matiére' => 'pa_matiere', 'Format' => 'pa_format', 'Couleurs' => 'pa_couleur');
      foreach ($attributes as $key => $value) :
      if($value = 'pa_couleur' )
      $filter= nap_filter_attribute($post_ID,$search[$value],$value,true);
      else
      $filter= nap_filter_attribute($post_ID,$search[$value],$value);
      endforeach; */
    /* if (isset($search['pa_format']) && $search['pa_format'] != '') {
      $format_value = get_the_terms($post_ID, 'pa_format');

      $filter = "hidden";
      if (is_array($format_value)) {
      foreach ($format_value as $key => $value) {

      if (stristr($search['pa_format'], $value->name)) {
      $filter = "selected";
      }
      }
      }
      }

      if (isset($search['pa_matiere']) && $search['pa_matiere'] != '') {
      $format_value = get_the_terms($post_ID, 'pa_matiere');

      $filter = "hidden";
      if (is_array($format_value)) {
      foreach ($format_value as $key => $value) {

      if (stristr($search['pa_matiere'], $value->name)) {
      $filter = "selected";
      }
      }
      }
      } */

    if (isset($filter))
        $class = $filter;
    $nap_article = '<article class = " visible row ' . $class . '">
    <a href="#"></a>
    <figure data-bg = "" class = "' . $size . ' transition">    
    <div class="abs-full article-bg transition"></div>';
    $nap_article.= $link;
    $nap_article.='<img class="transition" src="' . $image . '" alt="" title="">';
    if ($current_page == 'catalogue') :
        $nap_article .= '<ul class = "clearfix">';
        $variations = get_posts($args);
        $temp_colors = array();
        if (!empty($variations)) {
            foreach ($variations as $key => $value) {
                $color = nap_variation_color($value->ID);
                $format = nap_variation_format($value->ID);
                if (!in_array($color, $temp_colors)) {
                    $temp_colors[] = $color;

                    $nap_article.='<li data-link = "' . get_permalink($post_ID) . nap_variation_url($value->ID) . '" data-image = "' . get_the_post_thumbnail_url($value->ID, 'thumbnail') . '" data-color = "' . $color . '" data-format = "' . $format . '"></li> ';
                }
            }
        } else {
            $nap_article.='<li data-link = "' . get_permalink($post_ID) . '" data-image = "' . get_the_post_thumbnail_url($value->ID, 'thumbnail') . '" data-color = "' . get_post_thumbnail_id($post_ID) . '" data-format = ""></li> ';
        }
        $nap_article.='</ul>';
    endif;
    $nap_article.='</figure>
        
    <h3 class = "font-small" >' . $title_item . '</h3>
    </article>';

    return $nap_article;
}

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

function nap_upload_image($img) {
    return trim(strtolower($img));
}

function nap_variable_meta($varID, $meta) {
    return get_post_meta($varID, '_' . $meta, true);
}

add_action('wp_login_failed', 'my_front_end_login_fail');  // hook failed login

function my_front_end_login_fail($username) {
    $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
    // if there's a valid referrer, and it's not the default log-in screen
    if (!empty($referrer) && !strstr($referrer, 'wp-login') && !strstr($referrer, 'wp-admin')) {
        wp_redirect($referrer . '?login=failed');  // let's append some information (login=failed) to the URL for the theme to use
        exit;
    }
}

add_action('woocommerce_product_options_general_product_data', 'nap_general_product_data_custom_field');

function nap_general_product_data_custom_field($post_id) {

    woocommerce_wp_text_input(
            array(
                'id' => '_gencod_simple',
                'label' => __('Gencod(EAN13)', 'woocommerce'),
            )
    );


    woocommerce_wp_text_input(
            array(
                'id' => '_itf14_simple',
                'label' => __('ITF 14', 'woocommerce'),
            )
    );

    $option = nap_post_type_listing('fiche_technique');
    woocommerce_wp_text_input(
            array(
                'id' => 'fiche_simple_auto',
                'name' => 'fiche_simple_auto',
                'label' => __('Fiche technique', 'woocommerce'),
            )
    );
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function() {

            var posts = <?php echo json_encode($option); ?>;
            var data = [];
            jQuery.each(posts, function(index, value) {

                data.push({'label': value, 'value': index});
            });
            jQuery('input[name="fiche_simple_auto"]').click(function() {
                jQuery(this).val('');
            });
            jQuery('input[name="fiche_simple_auto"]').autocomplete({
                source: data,
                minLength: 1,
                select: function(event, ui) {
                    event.preventDefault();
                    jQuery(this).val(ui.item.label);
                    jQuery("#_fiche_simple").val(ui.item.value);
                }
            });
        });
    </script>
    <?php
    woocommerce_wp_hidden_input(
            array(
                'id' => '_fiche_simple',
                'label' => __('Fiche technique', 'woocommerce'),
                'name' => '_fiche_simple',
            )
    );
}

add_action('woocommerce_process_product_meta', 'nap_save_general_proddata_custom_field');

function nap_save_general_proddata_custom_field($post_id) {

    $select_fiche = $_POST['fiche_simple_auto'];
    if (!empty($select_fiche)) {
        update_post_meta($post_id, 'fiche_simple_auto', esc_attr($select_fiche));
    }

    $id_fiche = $_POST['_fiche_simple'];
    if (!empty($id_fiche)) {
        update_post_meta($post_id, '_fiche_simple', esc_attr($id_fiche));
    }

    $text_gencod = $_POST['_gencod_simple'];
    if (!empty($text_gencod)) {
        update_post_meta($post_id, '_gencod_simple', esc_attr($text_gencod));
    }

    $text_itf14 = $_POST['_itf14_simple'];
    if (!empty($text_itf14)) {
        update_post_meta($post_id, '_itf14_simple', esc_attr($text_itf14));
    }
}

session_start();
$ref = false;
//MS 2017-08-02 : Get referrer
function externe_referrer() {
    session_start();
    $url = $_SERVER['HTTP_REFERER'];
    $postid = url_to_postid($url);
    $notRefreshed = true;
    $uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' ||  $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache'); 
//The second parameter on print_r returns the result to a variable rather than displaying it
$RequestSignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));
if (($pageWasRefreshed || empty($url) )) // && (from-site) //$_SESSION['LastRequest'] == $RequestSignature 
{
   $ref = true;
}
else
{
    $ref = false;
    $_SESSION['LastRequest'] = $RequestSignature;
}
    return $ref;
}

function get_logged_user() {
    if (is_user_logged_in()) {
        global $current_user;
        get_currentuserinfo();
        if($current_user->user_lastname || $current_user->user_firstname){
            echo $current_user->user_lastname . ' ' . $current_user->user_firstname;
        }else{
            echo $current_user->user_login;
        }
        echo '<span class = "logout"><a href="' .  wp_logout_url( home_url() ) . '">déconnexion</a></span>';
    } else {
        echo '<a class="login" href="#">accès pro</a>';
    }
}
//remove margin top margin header Wordpress
add_action('get_header', 'my_filter_head');
function my_filter_head() {
remove_action('wp_head', '_admin_bar_bump_cb');
}
function nap_attribute_by_category($categorie, $attr) {

    $args = array(
        'post_type' => array('product', 'product_variation'),
        'numberposts' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'id',
                'terms' => $categorie,
                'operator' => 'IN',
            )
        )
    );
    $products = get_posts($args);
    $attribute = array();
    foreach ($products as $key => $value) {
        $list_attr = woocommerce_get_product_terms($value->ID, $attr, 'names');
        foreach ($list_attr as $key => $value) {
            $attribute[] = $value;
        }
    }
    return array_unique($attribute);
}

add_image_size('wordpress-thumbnail', 200, 200, FALSE);

function nap_selected_filter($search, $attribute) {
    if (isset($search) && stristr($search, $attribute)) :
        $filter_class = 'selected';
    else:
        $filter_class = '';
    endif;
    return $filter_class;
}

add_action('trash_fiche_technique', 'nap_trash_fiche_technique', 1, 1);

function nap_trash_fiche_technique($post_id) {

    $post = get_post($post_id);

    global $wpdb;
    $table = $wpdb->prefix . 'postmeta';
    $wpdb->delete($table, array('meta_key' => '_fiche_simple', 'meta_value' => $post_id));
    $wpdb->delete($table, array('meta_key' => '_var_fiche', 'meta_value' => $post_id));

    $wpdb->delete($table, array('meta_key' => 'fiche_simple_auto', 'meta_value' => $post->post_title));
    $wpdb->delete($table, array('meta_key' => 'fiche_var_auto', 'meta_value' => $post->post_title));
}


add_action( 'pre_get_posts', 'nap_change_filter_post' );
function nap_change_filter_post() {
    global $wp_query;
    if(is_admin()) {
        if(!empty($wp_query->query_vars['product_cat'])) {
            setcookie("product_cat", $wp_query->query_vars['product_cat']);
        }
        if(!isset($_GET['product_cat']) && ($_GET['post_type'] == 'product')) {
            $wp_query->query_vars['product_cat'] = $_COOKIE['product_cat'];
        }
        elseif(isset($_GET['product_cat']) && empty($_GET['product_cat'])) {
            setcookie("product_cat", $wp_query->query_vars['product_cat']);
        }
    }
}

function nap_show_associated_products() {
    $associated_products = '';
    
    global $product;

    $upsells = wc_products_array_orderby( array_filter( array_map( 'wc_get_product', $product->get_upsell_ids() ), 'wc_products_array_filter_visible' ), 'rand', 'desc' );
    
    $associated_products .= '<div class="suggest-header">
            <h2>Produits associés</h2>
            <span class="close-btn"></span>
        </div>
        <div class="product-list-content">';
    
    foreach ( $upsells as $upsell ) :
        $img = '';
        if(has_post_thumbnail($upsell->get_id()))
            $img = get_the_post_thumbnail($upsell->get_id(), 'medium');
        else { 
            $product = new WC_Product_Variable( $upsell->get_id() );
            $variations = $product->get_available_variations();
            if(isset($variations[0]))
                $img = get_the_post_thumbnail($variations[0]['variation_id'], 'medium');
        }
        $associated_products .= '<article class = "row full-width">
                <a href="#"></a>
                <figure>
                    '.$img.'
                </figure>
                <h3 class = "font-small" >'. $upsell->name .'</h3>
            </article>';
    endforeach;
            
    $associated_products .= '</div>';
    
    return $associated_products;
}