<?php
/*
    woocommerce hooks extensions
*/
if( ! defined( 'ABSPATH' ) ) exit;

new woo_hooks();
class woo_hooks {
    
    public $before_content = "";
    public $after_content = "";
    private static $wrapper_open = false;
    
    public static $before_html = "<div class='vc_row wpb_row vc_row-fluid row_xxl'><div class='wpb_column vc_column_container vc_col-sm-12'><div class='vc_column-inner '>";
    public static $after_html = "</div></div></div>";

    public static $before_html_gg = "<div>";
    public static $after_html_gg = "</div>";

    /* 
        Constructor 
    */
    public function __construct() {

        // enable theme support
        // https://woocommerce.wordpress.com/2017/02/28/adding-support-for-woocommerce-2-7s-new-gallery-feature-to-your-theme/
        add_action( 'after_setup_theme', array($this, 'add_woocommerce_support') );
        
        // adjust actions   
        // https://businessbloomer.com/category/woocommerce-tips/visual-hook-series/
        add_action( 'wp_loaded', array($this, 'mod_woocommerce_actions') );
        
        // add custom ajax button
        add_action( 'wp_ajax_greyd_woo_ajax', array($this, 'handle_add_to_cart_ajax') );
        add_action( 'wp_ajax_nopriv_greyd_woo_ajax', array($this, 'handle_add_to_cart_ajax') );

        // add the WooCommerce dynamic cart icons/items
        // https://slocumthemes.com/2015/06/how-to-display-shopping-cart-details-wordpress-menu/
        add_filter( 'wp_nav_menu_items', array($this, 'wc_nav_menu_items'), 10, 2 );
        add_filter( 'woocommerce_add_to_cart_fragments', array($this, 'wc_add_to_cart_fragments') );
        
        // woo script cleaner
        add_action( 'wp_enqueue_scripts', [$this, 'woocommerce_pagespeed'], 99 );
    }

    
    /*
        Enable theme support
    */
    public function add_woocommerce_support() {
        add_theme_support( 'woocommerce' );
    }
    
    /*
        Adjust actions
    */
    public function mod_woocommerce_actions() {

        /*
            General
        */
        // remove sidebar
        remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10);
        
        // replace Wrapper
        remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
        remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 20 );
        add_action( 'woocommerce_before_main_content', array($this, 'wc_wrapper_start'), 15 );
        add_action( 'woocommerce_after_main_content', array($this, 'wc_wrapper_end'), 25 );
        
        add_action( 'the_post', array($this, 'vc_frontend_start'), 99 );
        add_action( 'get_footer', array($this, 'vc_frontend_end'), 99 );
        
        // add inline scripts
        add_action( 'wp_enqueue_scripts', array($this, 'add_inline_styles') );

        
        /*
            Pages
        */
        // Shop page
        $this->edit_shop_page();
        // Product page
        $this->edit_product_page();
        // Checkout page
        $this->edit_checkout_page();
        // My account page
        $this->edit_account_page();
        
        /*
            GREYD Add-to-Cart Button
        */
        add_action( 'render_new_add_to_cart_ajax', array($this, 'render_add_to_cart_ajax'), 1 );
        
        /*
            Custom Template Hooks
        */
        $hooks = \vc\helper::get_dynamic_woocommerce_hooks();
        foreach ($hooks as $hook => $name) {
            add_action( $hook , array($this, 'add_dynamic_hooks') );
        }

        /**
         * Announcement box support for shop page
         */
        add_action( 'announcement_hook', array($this, 'add_announcement') );
    }
    

    
    /*
        General
    */
    public function vc_frontend_start( $post ) {
        if ( is_admin() || self::$wrapper_open ) return;
        if ( is_cart() || is_checkout() || is_account_page() ) {
            // debug( $post, true );
            $content = $post->post_content;

            if ( strpos($content, '[vc_row') === false && !is_greyd_blocks()) {
                self::$wrapper_open = true;
                echo self::$before_html;
            } else if (is_greyd_blocks()) {
                self::$wrapper_open = true;
                echo self::$before_html_gg;
            }
        }
    }
    public function vc_frontend_end() {
        if (self::$wrapper_open && !is_greyd_blocks()) {
            echo self::$after_html;
        } else if (self::$wrapper_open && is_greyd_blocks()) {
            echo self::$after_html_gg;
        }
    }

    
    // Wrapper
    public function wc_wrapper_start() {
        // get content from shop page
        $shop_page = get_post( get_option( 'woocommerce_shop_page_id' ) );

        if ( has_blocks($shop_page->post_content) ) {
            $content = do_blocks( $shop_page->post_content );
        } else {
            $content = do_shortcode( $shop_page->post_content );
        }

        if ( !is_shop() ) {
            // check if there are templates
            $template_name = "";
            if (is_product()) {
                $template_name = 'woo-product';
            }
            else if (is_product_category()) {
                // debug("shop category");
                $template_name = 'woo-product-category';
            }
            else if (is_product_tag()) {
                // debug("shop tag");
                $template_name = 'woo-product-tag';
            }
            // else {
            //     debug("shop something");
            // }
            if ($template_name != "") {
                $template = get_posts(array(
                    'name'        => $template_name,
                    'post_type'   => 'dynamic_template',
                    'post_status' => 'publish',
                    'numberposts' => 1
                ));
              
                if ($template && is_greyd_blocks()) {
                    $content = do_blocks('<!-- wp:greyd/dynamic {"template":"'.$template[0]->ID.'"} /-->');
                } else if ($template && !is_greyd_blocks()) {
                    $content = do_shortcode("[dynamic template='".$template_name."']");
                }  
            }

        }
        $content = explode('WOO_CONTENT', $content);
        $this->before_content = isset($content[0]) ? $content[0] : "";
        if ( is_greyd_blocks()) {
            $this->after_content = isset($content[1]) && !empty($content[1]) ? "<div class='after_woocommerce_content'>".$content[1]."</div>" : "";
        } else {
            $this->after_content = isset($content[1]) ? $content[1] : "";
        }
        
        echo $this->before_content;
        if ($this->after_content == "") {
            // open default wrapper
            if ( !is_greyd_blocks()) {
                self::$wrapper_open = true;
                echo self::$before_html;
            } elseif (is_greyd_blocks()) {
                self::$wrapper_open = true;
                echo self::$before_html_gg;
            }
        }
        echo "<div class='woo_wrapper gg'>";
    }
    public function wc_wrapper_end() {
        echo $this->after_content;
        if ($this->after_content == "") {
            // close default wrapper
            echo self::$after_html;
        }
    }
    
    // Inline Stylesheet
    public function add_inline_styles() {
        $style = "";
        
        // cart page
        if (is_cart()) {
            
            // thumbnails
            if ( !get_theme_mod('woo_enable_cart_image', 1) ) {
                $style .= '.shop_table .product-thumbnail { display: none !important; }';
            }
            
            // description
            $mode = get_theme_mod('woo_enable_cart_descr', 'on');
            if ( $mode !== 'on' ) {
                if ($mode === 'no_mobile') $style .= '@media (max-width: var(grid_md)) {';
                if ($mode === 'no_desktop') $style .= '@media (min-width: var(grid_md)) {';
                $style .= '.shop_table .product-name .item-desc { display: none !important; }';
                if ($mode === 'no_desktop' || $mode === 'no_mobile') $style .= '}';
            }
        }

        // checkout page
        if (is_checkout()) {
            // image
            $mode = get_theme_mod('woo_enable_summary_image', 'on');
            if ( $mode !== 'on' ) {
                if ($mode === 'no_mobile') $style .= '@media (max-width: var(grid_md)) {';
                if ($mode === 'no_desktop') $style .= '@media (min-width: var(grid_md)) {';
                $style .= '.woocommerce-checkout-review-order-table .wc-gzd-product-name-left { display: none !important; }';
                if ($mode === 'no_desktop' || $mode === 'no_mobile') $style .= '}';
            }

            // description
            $mode = get_theme_mod('woo_enable_summary_descr', 'on');
            if ( $mode !== 'on' ) {
                if ($mode === 'no_mobile') $style .= '@media (max-width: var(grid_md)) {';
                if ($mode === 'no_desktop') $style .= '@media (min-width: var(grid_md)) {';
                $style .= '.woocommerce-checkout-review-order-table .item-desc { display: none !important; }';
                if ($mode === 'no_desktop' || $mode === 'no_mobile') $style .= '}';
            }
        }
        
        // process & add inline style
        wp_add_inline_style( 'default_style', \processor::process_styles_string($style) );
    }
        
    /*
        Shop Page
    */
    public function edit_shop_page() {
        // remove breadcrumbs
        if (!get_theme_mod('woo_enable_breadcrumbs', 1))
            remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20 );
        // edit headlines
        add_filter( 'woocommerce_show_page_title', array($this, 'wc_show_page_title') );
        // remove description
        remove_action( 'woocommerce_archive_description', 'woocommerce_product_archive_description', 10 );
        if (!get_theme_mod('woo_enable_description', 1))
            remove_action( 'woocommerce_archive_description', 'woocommerce_taxonomy_archive_description', 10 );
        // remove result count
        if (!get_theme_mod('woo_enable_count', 1))
            remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 );
        // remove ordering
        if (!get_theme_mod('woo_enable_ordering', 1))
            remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30 );
        // remove pagination
        if (!get_theme_mod('woo_enable_pagination', 1))
            remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 );
        // edit pagination
        add_filter( 'woocommerce_pagination_args', 	array($this, 'wc_pagination') );
        
        // hide shop content
        add_action( 'woocommerce_before_main_content', array( $this, 'hide_shop_content' ), 99 );
    }
    
    public function hide_shop_content() {
        if ( is_shop() ) {
            $content = get_post( get_option('woocommerce_shop_page_id') )->post_content;

            if ( !empty($content) && !( (!empty($content) && strpos($content, 'WOO_CONTENT') !== false) || (!empty($content) && strpos($content, '[woo_content') !== false)) )  {
                echo '<style>.woo_wrapper { display: none !important; }</style>';
            }
        }
    }
    
    public function wc_show_page_title() {
        // return boolval(!is_shop());
        if (is_shop() && !get_theme_mod('woo_enable_shop_headline', 1)) return false;
        if (!is_shop() && !get_theme_mod('woo_enable_tax_headline', 1)) return false;
        return true;
    }
    
    public function wc_pagination( $args ) {
        $prev = get_theme_mod('woo_edit_pagination_prev','◂');
        $next = get_theme_mod('woo_edit_pagination_next','▸');
        // edit pagination
        $args['prev_text'] = $prev;
        $args['next_text'] = $next;
        return $args;
    }
        
    /*
        Product Page
    */
    public function edit_product_page() {
        // gallery
        $this->add_woocommerce_gallery_support();
        // remove images
        if (!get_theme_mod('woo_enable_images', 1))
            remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
        // add mobile add_to_cart button
        add_action( 'woocommerce_single_product_summary', array($this, 'wc_add_cart_button_mobile'), 15 );
        // remove meta data
        if (!get_theme_mod('woo_enable_meta', 1))
            remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );
        // remove tabs
        if (!get_theme_mod('woo_enable_tabs', 1))
            remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );        
        // remove upsell products
        if (!get_theme_mod('woo_enable_upsell', 1))
            remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 );
        // remove related products
        if (!get_theme_mod('woo_enable_related', 1))
            remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
        // edit layout
        add_action( 'woocommerce_before_single_product_summary', array($this, 'before_product_layout'), 9);
        add_action( 'woocommerce_after_single_product_summary', array($this, 'after_product_layout'), 1);

    }
    
    public function wc_add_cart_button_mobile() {
        $class = get_theme_mod('woo_product_mobile_button', 'hidden');
        echo '<div class="add_to_cart_top '.$class.'">';
            woocommerce_template_single_add_to_cart();
        echo '</div>';
    }
    
    public function add_woocommerce_gallery_support() {
        // enable support for zoom, lightbox and slider
        if (get_theme_mod('woo_enable_gallery', 1)) {
            add_theme_support( 'wc-product-gallery-zoom' );
            add_theme_support( 'wc-product-gallery-lightbox' );
        }
        else {
            add_filter( 'woocommerce_single_product_image_gallery_classes', array($this, 'wc_image_gallery_classes') );
        }
        if (get_theme_mod('woo_enable_slider', 1)) {
            add_theme_support( 'wc-product-gallery-slider' );
        }
    }
    
    public function wc_image_gallery_classes( $classes ) {
        $classes[] = "no-click";
        // debug($classes);
        return $classes;
    }
    
    public function before_product_layout() {
        $class = str_replace('-reverse', '', get_theme_mod('woo_product_layout', 'row'));
        echo "<div class='woo_product_layout_wrapper $class'>";
    }
    
    public function after_product_layout() {
        echo "</div>";
    }
        
    /*
        Checkout Page
    */
    public function edit_checkout_page() {
        
        // edit checkout fields
        // https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
        // https://rudrastyh.com/woocommerce/checkout-fields.html
        add_filter( 'woocommerce_before_checkout_form_cart_notices' , array($this, 'wc_edit_checkout_form_top'), 1 );
        add_filter( 'woocommerce_after_checkout_form' , array($this, 'wc_edit_checkout_form_bottom'), 99 );
        
        add_filter( 'woocommerce_default_address_fields' , array($this, 'wc_edit_checkout_default_fields') );
        add_filter( 'woocommerce_checkout_fields' , array($this, 'wc_edit_checkout_fields') );
        
        // remove additional information column
        if (get_theme_mod('woo_checkout_order_notes', 'hidden') == 'hidden' &&
            get_theme_mod('woo_checkout_order_refer', 'hidden') == 'hidden' &&
            get_theme_mod('woo_checkout_order_subscribe', 'hidden') == 'hidden') 
            add_filter( 'woocommerce_enable_order_notes_field', '__return_false', 9999 );

        // edit coupons messages on cart and checkout
        add_action('wp_footer', array($this, 'toggle_coupon_field'));
        
        /**
         * Put the WC-Germanized privacy checkboxes at the very bottom
         * 
         * @deprecated since Version 0.9.3 (public)
         */
        // // Remove the checkboxes
        // remove_action( 'woocommerce_review_order_after_payment', 'woocommerce_gzd_template_render_checkout_checkboxes', 10 );
        // // Re-add before submit button
        // add_action( 'woocommerce_gzd_review_order_before_submit', 'woocommerce_gzd_template_render_checkout_checkboxes', 10 );
    }
    
    public function wc_edit_checkout_form_top() {
        echo "<div class='checkout_layout ".get_theme_mod('woo_checkout_layout', 'column')."'>";
    }
    
    public function wc_edit_checkout_form_bottom() {
        echo "</div>";
    }
    
    public function wc_edit_checkout_default_fields($fields) {
        // defaults for billing and shipping
        // first_name, last_name
        // debug("names: ".get_theme_mod('woo_checkout_order_names', 'required'));
        if (get_theme_mod('woo_checkout_order_names', 'required') == 'hidden') {
            unset($fields['first_name']);
            unset($fields['last_name']);
        }
        else {
            $req = get_theme_mod('woo_checkout_order_names', 'required') == 'required' ? true : false;
            $fields['first_name']['required'] = $req;
            // $fields['first_name']['validate'] = $req;
            $fields['last_name']['required'] = $req;
            // $fields['last_name']['validate'] = $req;
        }
        // company
        // debug("company: ".get_option('woocommerce_checkout_company_field'));
        if (isset($fields['company'])) {
            $fields['company']['required'] = get_option('woocommerce_checkout_company_field') == 'required' ? true : false;
            // $fields['company']['validate'] = get_option('woocommerce_checkout_company_field') == 'required' ? true : false;
        }
        // country
        // debug("country: ".get_theme_mod('woo_checkout_order_country', 'optional'));
        if (get_theme_mod('woo_checkout_order_country', 'optional') == 'hidden') 
            unset($fields['country']);
        else {
            $fields['country']['required'] = get_theme_mod('woo_checkout_order_country', 'optional') == 'required' ? true : false;
            // $fields['country']['validate'] = get_theme_mod('woo_checkout_order_country', 'optional') == 'required' ? true : false;
        }
        // address_1 and address_2
        // debug("address1: ".get_theme_mod('woo_checkout_order_address1', 'optional'));
        // debug("address_2: ".get_option('woocommerce_checkout_address_2_field'));
        if (get_theme_mod('woo_checkout_order_address1', 'required') == 'hidden') 
            unset($fields['address_1']);
        else {
            $fields['address_1']['label'] = __('Straße und Hausnummer', 'core');
            $fields['address_1']['placeholder'] = '';
            $fields['address_1']['required'] = get_theme_mod('woo_checkout_order_address1', 'required') == 'required' ? true : false;
            // $fields['address_1']['validate'] = get_theme_mod('woo_checkout_order_address1', 'required') == 'required' ? true : false;
        }
        // city, state, postcode
        // debug("address_3: ".get_theme_mod('woo_checkout_order_address3', 'optional'));
        if (get_theme_mod('woo_checkout_order_address3', 'optional') == 'hidden') {
            unset($fields['postcode']);
            unset($fields['city']);
            unset($fields['state']);
        }
        else {
            $req = get_theme_mod('woo_checkout_order_address3', 'optional') == 'required' ? true : false;
            $fields['postcode']['required'] = $req;
            if ($req) $fields['postcode']['validate'] = false;
            // $fields['postcode']['validate'] = $req;
            $fields['city']['required'] = $req;
            // $fields['city']['validate'] = $req;
            $fields['state']['required'] = false;
            // $fields['state']['validate'] = false;
            // $fields['postcode']['class'][0] = 'form-row-first';
            // $fields['city']['class'][0] = 'form-row-last';
            // $fields['state']['priority'] = 95;
        }

        // debug($fields);
        return $fields;
    }
    
    public function wc_edit_checkout_fields($fields) {
        
        // title
        // only optional and required - for hidden, disable in gzd
        if (get_theme_mod('woo_checkout_order_title', 'optional') == 'hidden') {
            update_option('woocommerce_gzd_checkout_address_field', 'no');
            unset($fields['billing']['billing_title']);
            unset($fields['billing']['shipping_title']);
        } else {
            update_option('woocommerce_gzd_checkout_address_field', 'yes');
            // debug("title: ".get_theme_mod('woo_checkout_order_title', 'optional'));
            $req = get_theme_mod('woo_checkout_order_title', 'optional') == 'required' ? true : false;

            // billing
            $fields['billing']['billing_title']['required'] = $req;
            $classes = isset($fields['billing']['billing_title']['class']) ? (array) $fields['billing']['billing_title']['class'] : array();
            $classes[] = 'custom-select';
            $fields['billing']['billing_title']['class'] = $classes;

            // shipping
            $fields['shipping']['shipping_title']['required'] = $req;
            $classes = isset($fields['shipping']['shipping_title']['class']) ? (array) $fields['shipping']['shipping_title']['class'] : array();
            $classes[] = 'custom-select';
            $fields['shipping']['shipping_title']['class'] = $classes;
        }
        
        // email
        $fields['billing']['billing_email']['priority'] = 25;
        
        // phone
        // debug("phone: ".get_option('woocommerce_checkout_phone_field'));
        if (isset($fields['billing']['billing_phone'])) {
            $fields['billing']['billing_phone']['required'] = get_option('woocommerce_checkout_phone_field') == 'required' ? true : false;
            // $fields['billing']['billing_phone']['validate'] = get_option('woocommerce_checkout_phone_field') == 'required' ? true : false;
        }
        
        // order notes
        // debug("notes: ".get_theme_mod('woo_checkout_order_notes', 'hidden'));
        if (get_theme_mod('woo_checkout_order_notes', 'hidden') == 'hidden')
            unset($fields['order']['order_comments']);
        else {
            $fields['order']['order_comments']['required'] = get_theme_mod('woo_checkout_order_notes', 'hidden') == 'required' ? true : false;
            // $fields['order']['order_comments']['validate'] = get_theme_mod('woo_checkout_order_notes', 'hidden') == 'required' ? true : false;
        }

        // debug($fields);
        return $fields;
    }
    
    /*
        manually hide coupon field on cart and checkout page
        there is an option to fully disable the coupons in the settings
    */
    public function hide_coupon_field_on_cart( $enabled ) {
        // hide coupon field on cart page
        if ( is_cart() ) {
            $enabled = false;
        }
        return $enabled;
    }
    
    public function hide_coupon_field_on_checkout( $enabled ) {
        // hide coupon field on checkout page
        if ( is_checkout() ) {
            $enabled = false;
        }
        return $enabled;
    }
    
    /* toggle Coupon Field */
	public function toggle_coupon_field() {
        if (is_cart() || is_checkout()) {
            $event = is_cart() ? "wc_fragments_refreshed" : "updated_checkout";
            $price = apply_filters( 'raw_woocommerce_price', 0 );
            $price = apply_filters( 'formatted_woocommerce_price', number_format( $price, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() ), $price, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
            $price = sprintf( get_woocommerce_price_format(), get_woocommerce_currency_symbol(), $price );
            ?>
            <style>
                .woocommerce-form-coupon-toggle,
                div.woocommerce form.checkout_coupon,
                .woocommerce-cart-form .coupon {
                    display: none;
                }
            </style>
            <script type="text/javascript">
            (function($) { 
                $( document.body ).on( '<?=$event?>', function() {
                    // console.log('EVENT: <?=$event?>');
                    toggleCouponField();
                });
                function toggleCouponField() {
                    var price = $('.order-total .woocommerce-Price-amount.amount').text();
                    var targetprice = $("<div/>").html('<?=$price?>').text();
                    if (price != targetprice) {
                        // console.log("showing coupon fields");
                        $('.woocommerce-form-coupon-toggle, .woocommerce-cart-form .coupon').slideDown('');
                        $('#order_payment_heading, .woocommerce-checkout-payment').show();
                    }
                    else {
                        // console.log("hiding coupon fields");
                        $('.woocommerce-form-coupon-toggle, .woocommerce-cart-form .coupon').slideUp('');
                        $('#order_payment_heading, .woocommerce-checkout-payment').hide();
                    }
                }
                toggleCouponField();
            } )(jQuery);
            </script>
            <?php
        }
    }
    
    
    /*
        My Account Page
    */
    public function edit_account_page() {
        add_action( 'woocommerce_account_navigation', [$this, 'before_account_navigation'], 1 );
        // edit my-account tabs
        add_filter ( 'woocommerce_account_menu_items', [$this, 'edit_myaccount_tab'] );
    }
    
    public function before_account_navigation() {
        
        $headline = get_theme_mod('woo_account_headline', 'logout');
        if ( !empty($headline) && $headline !== 'none' ) {
            echo "<div class='myaccount_headline ".$headline."'>";
            
            $size = get_theme_mod('woo_account_headline_size', 'h4');
            echo "<".$size.">".sprintf(__("Hallo %s", 'core'), wp_get_current_user()->data->display_name)."!</".$size.">";
            
            if ($headline === 'logout')
                echo "<a href='".wc_logout_url()."' class='logout_link'>".__("Logout", 'core')."</a>";
            
            echo "</div>";
        }
        
        echo "<span hidden class='account_nav_layout' data-layout='".get_theme_mod('woo_account_layout', 'list')."'></span>";
    }
    
    public function edit_myaccount_tab( $menu_links ){
        // debug($menu_links);
        
        // Remove Logout link
        if ( get_theme_mod('woo_account_headline', 'logout') === 'logout' )
            unset( $menu_links['customer-logout'] );

        return $menu_links;
    }
        
    /*
        GREYD Add-to-Cart Button
    */
    public function render_add_to_cart_ajax($sets) {
        // debug($sets);
        
        $id = isset($sets['id']) ? esc_attr($sets['id']) : 0;
        // Exit when no Product ID or if not a Product
        $product = wc_get_product($id);
        if ($id == 0 || get_post_type($id) != 'product' || !$product) return;
        
        $href   = "_woo_ajax=" . $id . "|" . $sets['redirect'];
        $href  .= "|";
        $href  .= $sets['not_twice'] === 'true' ? '1' : '0';
        $href  .= "|";
        $href  .= $sets['clear'] === 'true' ? '1' : '0';
        $href  .= "_";
        
        // params
        $text   = isset($sets['text']) ? $sets['text'] : $product->add_to_cart_text();
        $class  = isset($sets['class']) ? esc_attr($sets['class']) : '';
        $style  = isset($sets['style']) ? $sets['style'] : '';
        // make button
        $add_to_cart_button = '<a href="'.$href.'"><span class="'.$class.'" style="'.$style.'">'.$text.'</span></a>';
        echo $add_to_cart_button;
    }
    
    // handle ajax request
    public function handle_add_to_cart_ajax() {
        $debug = false;
        
        check_ajax_referer( 'greyd_woo','_ajax_nonce', false );
        if ($debug) echo "\r\n\r\n";
        
        // define vars
        $data       = $_POST['data'];
        $product_id = isset($data['id'])        ? $data['id'] : null;
        $not_twice  = isset($data['not_twice']) ? filter_var($data['not_twice'], FILTER_VALIDATE_BOOLEAN) : false;
        $clear      = isset($data['clear'])     ? filter_var($data['clear'], FILTER_VALIDATE_BOOLEAN) : false;
        // no product set
        if ( empty($product_id) ) wp_die('error::no product id set');
        // not a product
        if ( get_post_type($product_id) != 'product' || !wc_get_product($product_id) )
            wp_die('error::'.sprintf('Post (ID: %s) is not a product', $product_id));

        // by default, item is added to cart
        $add_to_cart = true;
        
        // clear cart
        if ($clear) {
            WC()->cart->empty_cart();
            if ($debug) echo "\r\n\r\n"."Cart was successfully emptied";
        }
        // check for duplicates if it's not supposed to be added twice
        else if ($not_twice) {
            $product_cart_id = WC()->cart->generate_cart_id( $product_id );
            $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
            if ( $in_cart !== false ) {
                $add_to_cart = false;
                if ($debug) echo "\r\n\r\n".sprintf("Product (ID: %s) is already in cart.", $product_id);
            }
        }
        
        // add to cart
        if ($add_to_cart) {
            $cart_item_key = WC()->cart->add_to_cart( $product_id );
            if ($cart_item_key === false) wp_die('error::could not add product to cart');
            if ($debug) echo "\r\n\r\n".sprintf("Product (ID: %s) was added to cart", $product_id);
        }
        
        if ($debug) echo "\r\n\r\n";
        
        // return new cart count on success
        $count = WC()->cart->get_cart_contents_count();
        wp_die('success::'.$count);
    }
    
    /*
        Render Custom Template
    */
    public function add_dynamic_hooks($filter=true) {
        //debug($filter, true);
        // if ($filter !== false) { // use filter to not render content
            $template_name = current_filter();
            $template = get_posts(array(
                'name'        => $template_name,
                'post_type'   => 'dynamic_template',
                'post_status' => 'publish',
                'numberposts' => 1
            ));
            if ($template) echo do_shortcode('[dynamic template="'.current_filter().'" options="ignore_gutter"]');
        // }
    }
        
    /*
        Navbar
    */
    /* add WooCommerce dynamic cart item to the menu */
    public function wc_nav_menu_items( $items, $args, $ajax = false ) {
        
        // login link
        if ( property_exists( $args, 'menu' ) && empty($args->walker) ) {
            $slug = is_object($args->menu) ? $args->menu->slug : $args->menu;
            if ( $slug === get_theme_mod('woo_login_menu_location', 'none') ) {
                $css_class = 'menu-item';
                if (is_account_page()) $css_class .= ' current-menu-item';
                // make new cart item
                $item = "<li class='$css_class'>";
                    $item .= "<a href='" . esc_url( get_permalink( get_option('woocommerce_myaccount_page_id') ) ) . "'>";
                        $item .= is_user_logged_in() ? __('Mein Konto', 'core') : __('Login', 'core');
                    $item .= "</a>";
                $item .= "</li>";
                // add cart item
                if (get_theme_mod('woo_login_menu', 'right') == 'left') $items = $item.$items;
                else if (get_theme_mod('woo_login_menu', 'right') == 'right') $items = $items.$item;
            }
        }

        // cart icon
        if ( ( isset( $ajax ) && $ajax ) || ( property_exists( $args, 'theme_location' ) && $args->theme_location === 'main-menu' ) ) {
            if (!empty(get_theme_mod('woo_cart', false))) {
                $count = function_exists('WC') && WC()->cart ? intval( WC()->cart->get_cart_contents_count() ) : 0;
                $css_class = 'menu-item';
                if (is_cart()) $css_class .= ' current-menu-item';
                
                // cart is empty & disabled
                if ( get_theme_mod('woo_disable_cart_when_empty', false) && $count == 0 ) $css_class .= ' hidden';
                
                // make new cart item
                $item = "<li class='greyd_cart_nav_item $css_class'>";
                    $item .= "<a class='cart-contents' href='" . esc_url( wc_get_cart_url() ) . "'>";
                        $item .= "<span class='icon_cart'></span>";
                        if ($count > 0) $item .= "<span class='woo_cart_count'>" . WC()->cart->get_cart_contents_count() . "</span>";
                        if ($count > 0 && get_theme_mod('woo_enable_cart_price', 0)) $item .= "<small> (" . wp_kses_data( WC()->cart->get_cart_total() ) . ")</small>";
                    $item .= "</a>";
                $item .= "</li>";
                // add cart item
                if (get_theme_mod('woo_cart') == 'left') $items = $item.$items;
                else if (get_theme_mod('woo_cart') == 'right') $items = $items.$item;
            }
        }
        return $items;
    }
    
    /* updates WooCommerce dynamic cart link contents when an item is added via AJAX. */
    public function wc_add_to_cart_fragments( $fragments ) {
        // Add our fragment
        $fragments['li.menu-item-type-woocommerce-cart'] = $this->wc_nav_menu_items( '', new stdClass(), true );
        return $fragments;
    }
    
    
    /*
        Pagespeed Anpassungen
    */
    public function woocommerce_pagespeed() {
        
        $webshop_setting = \basics::get_setting( array('site', 'webshop') );
        if ( empty($webshop_setting) || !isset($webshop_setting['pagespeed']) || $webshop_setting['pagespeed'] !== 'true' ) return;
        
        // VC
        wp_dequeue_script( 'vc_vendor_woocommerce_frontend' );
        wp_dequeue_script( 'vc_vendor_woocommerce_add_to_cart' );
        
        // WOO
        // Remove the generator tag
        remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
        
        // first check that woo exists to prevent fatal error
        if ( function_exists('is_woocommerce') ) {
            // Unless we're in the store, remove all the cruft!
            if ( !is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page() ) {
                
                // Germanized
                wp_dequeue_style( 'woocommerce-gzd-layout' );
                
                // source:
                // https://gist.github.com/gregrickaby/2846416
                wp_dequeue_style( 'woocommerce_frontend_styles' );
                wp_dequeue_style( 'woocommerce-general');
                wp_dequeue_style( 'woocommerce-layout' );
                wp_dequeue_style( 'woocommerce-smallscreen' );
                wp_dequeue_style( 'woocommerce_fancybox_styles' );
                wp_dequeue_style( 'woocommerce_chosen_styles' );
                wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
                wp_dequeue_script( 'selectWoo' );
                wp_deregister_script( 'selectWoo' );
                wp_dequeue_script( 'wc-add-payment-method' );
                wp_dequeue_script( 'wc-lost-password' );
                wp_dequeue_script( 'wc_price_slider' );
                wp_dequeue_script( 'wc-single-product' );
                wp_dequeue_script( 'wc-add-to-cart' );
                wp_dequeue_script( 'wc-cart-fragments' );
                wp_dequeue_script( 'wc-credit-card-form' );
                wp_dequeue_script( 'wc-checkout' );
                wp_dequeue_script( 'wc-add-to-cart-variation' );
                wp_dequeue_script( 'wc-single-product' );
                wp_dequeue_script( 'wc-cart' );
                wp_dequeue_script( 'wc-chosen' );
                wp_dequeue_script( 'woocommerce' );
                wp_dequeue_script( 'prettyPhoto' );
                wp_dequeue_script( 'prettyPhoto-init' );
                wp_dequeue_script( 'jquery-blockui' );
                wp_dequeue_script( 'jquery-placeholder' );
                wp_dequeue_script( 'jquery-payment' );
                wp_dequeue_script( 'fancybox' );
                wp_dequeue_script( 'jqueryui' );
            }
        }
    }

    /**
     * Add the announcement box on the shop page
     */
    public function add_announcement() {
        if ( is_shop() ) {
            do_action('render_announcement', get_option( 'woocommerce_shop_page_id' ));
        }
    }
}