<?php


/**
 * footer...
 */
add_action( 'init', 'jk_remove_storefront_header_search' );
function jk_remove_storefront_header_search() {
remove_action( 'storefront_header', 'storefront_product_search',    40 );
}


add_action( 'init', 'custom_remove_footer_credit', 10 );

function custom_remove_footer_credit () {
    remove_action( 'storefront_footer', 'storefront_credit', 20 );
    add_action( 'storefront_footer', 'custom_storefront_credit', 20 );
}

function custom_storefront_credit() { ?>
    <div class="site-info">
        <div class="footer-logo-row">
            <div class="footer-logo-column">
                <a href="http://www.getchanged.net/" target="_blank">
                    <img  src="<?php echo home_url(); ?>/wp-content/uploads/2018/06/buttons_footer1.gif" alt="">
                </a>
            </div>
            <div class="footer-logo-column link-best">
                <a href="https://bestswiss.ch/marken/erfolg" target="_blank">
                    <img src="<?php echo home_url(); ?>/wp-content/uploads/2018/06/buttons_footer2.png"  alt="">
                </a>
            </div>
            <div class="footer-logo-column link-pci">
                <a href="http://www.acertigo.com/pci-zertifizierung/pci-im-ueberblick/" target="_blank">
                    <img  src="<?php echo home_url(); ?>/wp-content/uploads/2018/06/buttons_footer3.gif"  alt="">
                </a>
            </div>
            <div class="social-footer-wrap">
                <ul class="custom-footer-menu social-custom-menu">
                        <li><a class="fb-icon" href="https://www.facebook.com/erfolg.label" target="_blank"></a></li>
                        <li><a href="http://www.erfolg-label.ch/blog/feed/" class="rss-icon" target="_blank"></a></li>
                        <li><a href="https://twitter.com/erfolglabel" class="twitter-icon" target="_blank"></a></li>
                        <li><a href="https://www.instagram.com/erfolglabel/" class="instagram-icon" target="_blank"></a></li>
                </ul>
            </div>
        </div>
    </div><!-- .site-info -->
<?php
}



/**
 * Rename "home" in breadcrumb
 */
add_filter( 'woocommerce_breadcrumb_defaults', 'wcc_change_breadcrumb_home_text', 20 );
function wcc_change_breadcrumb_home_text( $defaults ) {
    $defaults['home'] = 'Erfolg';
    return $defaults;
}



/*
 * change add to cart button
 */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'erfolg_woo_custom_cart_button_text' );
add_filter( 'woocommerce_product_add_to_cart_text', 'erfolg_woo_custom_cart_button_text' );
function erfolg_woo_custom_cart_button_text() {
    return __( 'In den Warenkorb', 'erfolg' );
}


add_filter( 'woocommerce_cart_totals_order_total_html', 'custom_total_tax' );
function custom_total_tax() {

    $value = '<strong>' . WC()->cart->get_total() . '</strong> '; 
 
    // If prices are tax inclusive, show taxes here 
    if ( wc_tax_enabled() && WC()->cart->tax_display_cart == 'incl' ) { 
        $tax_string_array = array(); 
   
        if ( get_option( 'woocommerce_tax_total_display' ) == 'itemized' ) { 
            foreach ( WC()->cart->get_tax_totals() as $code => $tax ) 
                $tax_string_array[] = sprintf( '%s %s', $tax->formatted_amount, $tax->label ); 
        } else { 
            $tax_string_array[] = sprintf( '%s %s', wc_price( WC()->cart->get_taxes_total( true, true ) ), WC()->countries->tax_or_vat() ); 
        } 
   
        if ( ! empty( $tax_string_array ) ) { 
            $taxable_address = WC()->customer->get_taxable_address(); 
            $estimated_text = WC()->customer->is_customer_outside_base() && ! WC()->customer->has_calculated_shipping() 
                ? sprintf( ' ' . __( 'estimated for %s', 'woocommerce' ), WC()->countries->estimated_for_prefix( $taxable_address[0] ) . WC()->countries->countries[ $taxable_address[0] ] ) 
                : ''; 
            $value .= '<small class="includes_tax">' . sprintf( __( '(%s)', 'woocommerce' ), 'inkl. 8.1% Mehrwertsteuer' . $estimated_text ) . '</small>'; 
        } 
    } 

    return $value;
}


add_filter( 'woocommerce_get_formatted_order_total', 'custom_formatted_order_total', 10, 1 );
function custom_formatted_order_total( $formatted_total ) {

    $dom = new DOMDocument();
    @ $dom->loadHTML($formatted_total);
    $ps = $dom->getElementsByTagName('small');
    if($ps) {
        $first_para = $ps->item(0);
        if($first_para) {
            $first_para->nodeValue = "(inkl. 8.1% Mehrwertsteuer)";

            $output = @ $dom->saveHTML();
            return $output;
        } else {
            return $formatted_total;
        }
    } else {
        return $formatted_total;
    }
}


function custom_wc_ajax_variation_threshold( $qty, $product ) {
    return 10;
}

add_filter( 'woocommerce_ajax_variation_threshold', 'custom_wc_ajax_variation_threshold', 10, 2 );

//remove_filter( 'the_content', 'wpautop' );


add_action( 'admin_init', 'erfolg_disable_autosave' );
function erfolg_disable_autosave() {
        wp_deregister_script( 'autosave' );
}


add_action( 'init', 'erfolg_stop_heartbeat', 1 );
function erfolg_stop_heartbeat() {
    wp_deregister_script('heartbeat');
}

add_filter( 'gettext', 'customizing_variable_product_message', 97, 3 );
function customizing_variable_product_message( $translated_text, $untranslated_text, $domain ) {
    if ($untranslated_text == 'Please select some product options before adding this product to your cart.') {
        $translated_text = __( 'Bitte zuerst die Farbe auswählen.', $domain );
    }
    return $translated_text;
}


function wc_get_gallery_image_html_custom( $attachment_id, $main_image = false ) {
    $flexslider        = (bool) apply_filters( 'woocommerce_single_product_flexslider_enabled', get_theme_support( 'wc-product-gallery-slider' ) );
    $gallery_thumbnail = wc_get_image_size( 'gallery_thumbnail' );
    $thumbnail_size    = apply_filters( 'woocommerce_gallery_thumbnail_size', array( $gallery_thumbnail['width'], $gallery_thumbnail['height'] ) );
    $image_size        = apply_filters( 'woocommerce_gallery_image_size', $flexslider || $main_image ? 'woocommerce_single' : $thumbnail_size );
    $full_size         = apply_filters( 'woocommerce_gallery_full_size', apply_filters( 'woocommerce_product_thumbnails_large_size', 'full' ) );
    $thumbnail_src     = wp_get_attachment_image_src( $attachment_id, $thumbnail_size );
    $full_src          = wp_get_attachment_image_src( $attachment_id, $full_size );
    $image             = wp_get_attachment_image( $attachment_id, 'full', false, array(
        'title'                   => get_post_field( 'post_title', $attachment_id ),
        'data-caption'            => get_post_field( 'post_excerpt', $attachment_id ),
        'data-src'                => $full_src[0],
        'data-large_image'        => $full_src[0],
        'data-large_image_width'  => $full_src[1],
        'data-large_image_height' => $full_src[2],
        'class'                   => $main_image ? 'wp-post-image' : '',
    ) );

    return '<div data-thumb="' . esc_url( $thumbnail_src[0] ) . '" class="woocommerce-product-gallery__image er"><a href="' . esc_url( $full_src[0] ) . '">' . $image . '</a></div>';
}

/*
 * change out of stock message
 */
add_filter('woocommerce_get_availability_text', function($text, $product) {
    if (!$product->is_in_stock()) {
        $text = __( 'In dieser Grösse leider nicht verfügbar', 'erfolg' );
    }
    return $text;
}, 10, 2);



function custom_category_order( $query ) {
    if ( $query->is_tax('product_cat')  ) {
        $query->set( 'posts_per_page', -1 );
        if ( !isset( $_GET['orderby'] ) ) { //orderby is used when showing on sale products. so when we don't have that, we order by sku.
            $query->set( 'orderby', 'meta_value_num' );
            $query->set( 'meta_key', '_sku' );
            $query->set( 'order', 'DESC' );
        } else {
            
        }
        //$query->set( 'post__not_in', '' );

    }
}
add_action( 'pre_get_posts', 'custom_category_order' );


function test_232323232sdfghj() {

    if ( isset( $_GET['dev2212121'] ) ) {
        global $wp_query;
        echo '<pre>';
        print_r( $wp_query );
        echo '</pre>';
    }
}
//add_filter( 'wp_footer', 'test_232323232sdfghj' );


/*
 * new rules for template2020 landing home
 */
class Ergolg_Custom_Template {
    //
    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'style' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'script' ) );
    }

    public function style() {
        wp_enqueue_style( 'roboto-font2020', 'https://fonts.googleapis.com/css?family=Roboto&display=swap&subset=latin-ext' ) ;
        wp_enqueue_style( 'template2020slick-erfolg', get_stylesheet_directory_uri() . '/custom_template.css?v=1' );
    }

    public function script() {
        wp_enqueue_script ( 'template2020temp-script', get_stylesheet_directory_uri() . '/js/temp.js' );
        wp_enqueue_script ( 'template2020slick-script', get_stylesheet_directory_uri() . '/js/slick.min.js' );
        wp_enqueue_script ( 'template2020-script', get_stylesheet_directory_uri() . '/js/custom-template.js', array(), '1.0.1', true );
    }
}
new Ergolg_Custom_Template();

add_image_size( 'variable-erfolg-size', 128, 28, true ); // 220 pixels wide by 180 pixels tall, hard crop mode
add_image_size( 'slider-collection-size', 800 ); // 220 pixels wide by 180 pixels tall, hard crop mode


function erfolg_archive_collection( $atts ) {
    ob_start(); 
    $loop = $atts['loop'];
    $interval = $atts['interval'];
    $page_id = $atts['id'];
    $metas = get_field( 'slider', intval( $page_id ) );


    //if ( isset( $_GET['devi23r34r3'] ) ) :
    ?>
    
    <div class="collection-slider-wrapper" data-loop="<?php echo $loop; ?>" data-interval="<?php echo $interval; ?>">
        <div class="collection-slider">
            <?php
                foreach ($metas as $meta_set) { ?>
                    <div class="collection-slide">
                        <img src="<?php echo $meta_set['image']['sizes']['slider-collection-size']; ?>">
                    </div>
                <?php }
            ?>
        </div>
    </div>
    
    <?php 
    //endif;
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
add_shortcode( 'archive_collection', 'erfolg_archive_collection' );
function test_shortcode_erfolg() {
    if ( isset( $_GET['devi23r34r3'] ) ) {
        
        global $wp_query;
        echo '<pre>';
        print_r( $wp_query );
        echo '</pre>';
    }
}
// add_filter( 'wp_footer', 'test_shortcode_erfolg' );

// https://redmine.reea.net/issues/118779#change-565871

function redirect_from_konto() {
    if ( is_page( 'mein-konto-2' ) ) {
        wp_redirect( home_url( '' ) );
        exit();
    }
}

//add_action( 'template_redirect', 'redirect_from_konto' );


// add_action( 'wp_authenticate' , 'check_custom_authentication' );
  function check_custom_authentication ( $username ) {

    
     $user = new WP_User($username);
     $user_role_member=$user->roles[0];



    if( $user_role_member !== 'administrator' ){
        session_destroy();
        wp_redirect( home_url() );
        exit;
    }

 }


function check_server_date() {
    
    echo date('l jS \of F Y h:i:s A');
}
if ( isset( $_GET['for_erfolg_eyes_only'] ) ) {
    add_filter( 'wp_footer', 'check_server_date' );
}


class Erfolg_Checkout {
    public function __construct() {
        add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );


        add_filter( 'woocommerce_checkout_fields' , array( $this, 'custom_order_notes' ) );


        add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'order_note_save' ), 10, 2 );

    }


    public function custom_order_notes( $fields ) {
        $fields['billing']['new_order_notes'] = array(
           'type' => 'textarea',
           'label' => 'Bestellhinweise ',
           'placeholder' => 'Anmerkungen zu Ihrer Bestellung, z.B. besondere Hinweise für die Lieferung.',
           'class' => array('form-row-wide'),
           'clear' => true,
           'priority' => 999,
        );
        return $fields;
    }


    public function order_note_save( $order_id, $data ) {
        if ( ! is_object( $order_id ) ) {
           $order = wc_get_order( $order_id );
        }
        $order->set_customer_note( isset( $data['new_order_notes'] ) ? $data['new_order_notes'] : '' );
        wc_create_order_note( $order_id, $data['new_order_notes'], true, true );
        $order->save();
     }

}

new Erfolg_Checkout();

add_filter('pre_get_posts','erfolg_category_filter');

function erfolg_category_filter($query) {
    if ( $query->is_tax( 'product_cat') && $query->is_main_query() ) {
        $filter_cat = get_query_var( 'f', false );
        /*echo '<pre>asdf';
        echo($filter_cat);*/
        if($filter_cat){
            $query->set( 'tax_query', array(
                'relation' => 'AND',
                array(
                    'taxonomy'  => 'product_cat',
                    'field'     => 'id',
                    'terms'     => array($filter_cat),
                    'operator'  => 'IN'
                ),
            ));
        }
    }
}
function erfolg_add_query_vars( $qvars ) {
    $qvars[] = 'f';
    return $qvars;
}
add_filter( 'query_vars', 'erfolg_add_query_vars' );

function custom_woocommerce_product_description_and_variants() {
    global $product;

    // Display the product short description
    if ( $product->get_short_description() ) {
        echo '<div class="woocommerce-product-description">';
       // echo wp_trim_words( $product->get_short_description(), 20 ); // Limit to 20 words
        echo '</div>';
    } else {
        echo '<div class="woocommerce-product-description">';
        //echo wp_trim_words( $product->get_description(), 20 ); // Fallback to full description
        echo '</div>';
    }


    // Check if product is variable
    if ( $product->is_type( 'variable' ) ) {
        $available_variations = $product->get_available_variations();
        $attributes = $product->get_variation_attributes();

        // Assuming 'pa_color' is the attribute for color
        if ( isset( $attributes['pa_color'] ) ) {
            $color_attribute = $attributes['pa_color'];
            $displayed_colors = array(); // Array to store already displayed colors

            echo '<ul class="variable-items-wrapper">';
            
            $max_display = 3; // Maximum number of swatches to display
            $counter = 0; // Counter to track displayed colors

            foreach ( $available_variations as $variation ) {
                $variation_color = $variation['attributes']['attribute_pa_color']; // Adjust for your attribute slug

                // Check if this color has already been displayed
                if ( ! in_array( $variation_color, $displayed_colors ) ) {
                    // Retrieve the image for each color option
                    $image_id = $variation['image_id'];
                    if ( $image_id ) {
                        if ( $counter < $max_display ) {
                            $image_url = wp_get_attachment_url( $image_id );
                            echo '<li class="variable-item"><div class="variable-item-contents">';
                            echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( $variation_color ) . '" />';
                            echo '</div></li>';
                        }
                        $counter++;

                        // Add this color to the displayed list
                        $displayed_colors[] = $variation_color;
                    }
                }
            }

            // If there are more colors, show a "+" sign
            if ( $counter > $max_display ) {
                echo '<li class="variable-item">+</li>';
            }

            echo '</ul>';
        }
    }
}
add_action( 'woocommerce_after_shop_loop_item_title', 'custom_woocommerce_product_description_and_variants', 20 );
