/* Shortcode voor begroeting per dagdeel.
*/

function hello_nl (){
$time = date('H');
    if ($time < 12) {
       $greeting = "Goedemorgen";
       }
elseif ($time >= 12 && $time < 18){
       $greeting = "Goedemiddag";
       }
elseif ($time >= 18 && $time < 23){
       $greeting = "Goedenavond";
       }
  else {
       $greeting = "Hallo";
       }
echo esc_attr( $greeting );

}
add_shortcode ( 'hello_nl', 'hello_nl' );

                                   
                                   
/* Shortcodes voor het verkrijgen van de gebruikers eerste en tweede naam en het e-mailadres.
*/

function firstname_shortcode_func() {
	ob_start();
	$user_info = get_userdata(get_current_user_id());
      $first_name = $user_info->first_name;
      echo "$first_name";
	$output = ob_get_clean();
    return $output;
}
add_shortcode('user_firstname', 'firstname_shortcode_func');

function lastname_shortcode_func() {
	ob_start();
	$user_info = get_userdata(get_current_user_id());
      $last_name = $user_info->last_name;
      echo "$last_name";
	$output = ob_get_clean();
    return $output;
}
add_shortcode('user_lastname', 'lastname_shortcode_func');

function email_shortcode_func() {
	ob_start();
	$user_info = get_userdata(get_current_user_id());
      $email = $user_info->user_email;
      echo "$email";
	$output = ob_get_clean();
    return $output;
}
add_shortcode('user_email', 'email_shortcode_func');



/* Shortcode voor het tonen van openingstijden.
*/
date_default_timezone_set('Europe/Amsterdam');

function customer_service_phone (){
    $dateOfWeek = date('w');
    $time = date('H');
    if ($dateOfWeek == '1' && $time > '12' && $time < '17') {
        $availability = "We zijn vandaag bereikbaar tot 17.00 uur.";
    } elseif ($dateOfWeek > '1' && $dateOfWeek < '6' && $time > '8' && $time < '17'){
        $availability = "We zijn vandaag bereikbaar tot 17.00 uur.";
    } else {
        $availability = "We zijn momenteel gesloten. Stuur een e-mail en we nemen z.s.m. contact met je op.";
    }
    echo esc_attr( $availability );
}
add_shortcode ( 'availability_phone', 'customer_service_phone' );



/* Shortcode voor het weergeven van (gratis) verzenden tekst op bijv. de cart page.
*/
function custom_message() {
    // Initialize
    $message = __( '', 'woocommerce' );
    
    // True
    if ( WC()->cart ) {
        // Change this to your free shipping threshold excl. vat
        $min_amount = 32.23;
        
        // Get cart subtotal
        $subtotal = WC()->cart->get_subtotal();

        if ( $subtotal < $min_amount ) {
            $message = sprintf( __( '', 'woocommerce' ), wc_price( $min_amount - $subtotal ) );
        } else {
            $message = __( 'Bestel nu en betaal <strong>geen</strong> verzendkosten.', 'woocommerce' );
        }
    }
    
    return $message;
}

// Refreshing on cart ajax events
function filter_woocommerce_add_to_cart_fragments( $fragments ) {    
    $fragments['div.display-message'] = '<div class="display-message">' . custom_message() . '</div>';
    
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1 );

// Shortcode
function display_my_message() {
    return '<div class="display-message">' . custom_message() . '</div>';
} 
// Register shortcode
add_shortcode( 'display_message', 'display_my_message' );




/* Shortcode voor "Dit product wordt gratis verzonden" zodra de productprijs boven het minimale bedrag voor gratis verzenden ligt t.b.v. op product pagina. Anders wordt er een melding weergegeven dat er gratis verzending is vanaf x bedrag.
*/
function shortcode_freeshipping( $atts ) {
    // Only on single product pages
    if( ! is_product() ) return;

    // Shortcode attributes
    $atts = shortcode_atts( array(
        'price' => 38.99 // Shipping price incl. vat
    ), $atts, 'freeshipping' );

    global $product;

    if( ! is_object($product) )
        $product = wc_get_product( get_the_id() );

    if( $product->get_price() > $atts['price'] ) {
        return __( 'Dit product wordt <strong>gratis</strong> verzonden', 'woocommerce' );
    } else {
        return __( '<strong>Gratis</strong> verzending vanaf € 39,-', 'woocommerce' );
    }
}
add_shortcode('shipping_shoutout', 'shortcode_freeshipping');



/* Verwijder prijs bij variabele producten en toon deze als normale prijs na selectie.
*/

add_action('woocommerce_before_add_to_cart_form', 'selected_variation_price_replace_variable_price_range');
function selected_variation_price_replace_variable_price_range(){
    global $product;

    if( $product->is_type('variable') ):
    ?><style> .woocommerce-variation-price {display:none;} </style>
    <script>
    jQuery(function($) {
        var p = 'p.price'
            q = $(p).html();

        $('form.cart').on('show_variation', function( event, data ) {
            if ( data.price_html ) {
                $(p).html(data.price_html);
            }
        }).on('hide_variation', function( event ) {
            $(p).html(q);
        });
    });
    </script>
    <?php
    endif;
}




/* Verberg verzendmethodes zodra gratis verzenden beschikbaar is.
*/

add_filter( 'woocommerce_package_rates', 'hide_other_shipping_when_free_is_available', 100, 2 );

function hide_other_shipping_when_free_is_available( $rates, $package ) {

    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}




/* Verander de dropdown text "Kies een optie" bij variabele producten naar "Kies {eigenschap naam}".
*/
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 'cinchws_filter_dropdown_args', 10 );

function cinchws_filter_dropdown_args( $args ) {
    $var_tax = get_taxonomy( $args['attribute'] );
    $args['show_option_none'] = apply_filters( 'the_title', $var_tax->labels->name );
    return $args;
}




/* Winkelwagen met één druk op de knop legen.
*/
add_action( 'woocommerce_cart_coupon', 'custom_woocommerce_empty_cart_button' );
function custom_woocommerce_empty_cart_button() {
	echo '<a href="' . esc_url( add_query_arg( 'empty_cart', 'yes' ) ) . '" class="button" title="' . esc_attr( 'Winkelmandje legen', 'woocommerce' ) . '">' . esc_html( 'Winkelmandje legen', 'woocommerce' ) . '</a>';
}
add_action( 'wp_loaded', 'custom_woocommerce_empty_cart_action', 20 );
function custom_woocommerce_empty_cart_action() {
	if ( isset( $_GET['empty_cart'] ) && 'yes' === esc_html( $_GET['empty_cart'] ) ) {
		WC()->cart->empty_cart();
		$referer  = wp_get_referer() ? esc_url( remove_query_arg( 'empty_cart' ) ) : wc_get_cart_url();
		wp_safe_redirect( $referer );
	}
}



/* Volume korting gebaseerd aan de hand van het gewicht in de winklwagen met melding in winkelwagen hoeveel nog te besteden voor x korting.
*/
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_discount', 30, 1 );
function shipping_weight_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_weight   = $cart->get_cart_contents_weight();
    $cart_subtotal = $cart->get_subtotal(); // Or $cart->subtotal;
    $percentage    = 0;

    if ( $cart_weight >= 10 && $cart_weight < 30 ) 
    {
        $percentage       = 5;
        $remaining_weight = 30 - $cart_weight;
        $next_percent     = 7.5;
    } 
    elseif ( $cart_weight >= 30 && $cart_weight < 70 ) 
    {
        $percentage       = 7.5;
        $remaining_weight = 70 - $cart_weight;
        $next_percent     = 10;
    } 
    elseif ( $cart_weight >= 70 && $cart_weight < 130 ) 
    {
        $percentage       = 10;
        $remaining_weight = 130 - $cart_weight;
        $next_percent     = 12.5;
    } 
    elseif ( $cart_weight >= 130 && $cart_weight < 200 ) {
        $percentage       = 12.5;
        $remaining_weight = 200 - $cart_weight;
        $next_percent = 15;
    } 
    elseif ( $cart_weight >= 200 ) 
    {
        $percentage       = 15;
        $next_percent     = false;
    } 
    else 
    {
        $next_percent = 5;
        $remaining_weight = 10 - $cart_weight;
    }

    // Apply a calculated discount based on weight
    if( $percentage > 0 ) {
        $discount = $cart_subtotal * $percentage / 100;
        $cart->add_fee( sprintf( __( 'Volumekorting %s', 'woocommerce' ), $percentage.'%'), -$discount );
    }

    if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
        return;

    // Display a custom message
    if ( is_cart() && $next_percent ) { 
        wc_add_notice( sprintf( 
            __("Bestel nog %s extra en krijg %s korting!", "woocommerce"), 
            wc_format_weight($remaining_weight), $next_percent.'%'
        ), 'notice' );
    }
}



/* Vereis minimum gewicht in de winkelwagen om te kunnen afrekenen.
*/
add_action( 'woocommerce_check_cart_items', 'cldws_set_weight_requirements' );
    function cldws_set_weight_requirements() {
     // Only run in the Cart or Checkout pages
     if( is_cart() || is_checkout() ) {
     global $woocommerce;
     // Set the minimum weight before checking out
     $minimum_weight = 10;
     // Get the Cart's content total weight
     $cart_contents_weight = WC()->cart->cart_contents_weight;
     // Compare values and add an error is Cart's total weight
     if( $cart_contents_weight < $minimum_weight  ) {
     // Display our error message
     wc_add_notice( sprintf('Om je bestelling af te ronden dien je minimaal %s%s te bestellen. '
     . 'Je hebt nu %s%s in je winkelmandje.',
     $minimum_weight,
     get_option( 'woocommerce_weight_unit' ),
     $cart_contents_weight,
     get_option( 'woocommerce_weight_unit' ),
     get_permalink( wc_get_page_id( 'shop' ) )
     ),
     'error' );
// Removing the Proceed to checkout button from the Cart page
      remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
    }
	 }
     
    }
    

/* Gewicht bestelling tonen in backend orderoverzicht.
*/
// Store cart weight in the database
add_action('woocommerce_checkout_update_order_meta', 'woo_add_cart_weight');

function woo_add_cart_weight( $order_id ) {
    global $woocommerce;
    
    $weight = $woocommerce->cart->cart_contents_weight;
    update_post_meta( $order_id, '_cart_weight', $weight );
}

// Add order new column in administration
add_filter( 'manage_edit-shop_order_columns', 'woo_order_weight_column', 20 );

function woo_order_weight_column( $columns ) {

	$offset = 8;
	$updated_columns = array_slice( $columns, 0, $offset, true) +
	array( 'total_weight' => esc_html__( 'Weight', 'woocommerce' ) ) +
	array_slice($columns, $offset, NULL, true);

	return $updated_columns;
}

// Populate weight column
add_action( 'manage_shop_order_posts_custom_column', 'woo_custom_order_weight_column', 2 );

function woo_custom_order_weight_column( $column ) {
	global $post;
 
	if ( $column == 'total_weight' ) {
		$weight = get_post_meta( $post->ID, '_cart_weight', true );
		if ( $weight > 0 )
			print $weight . ' ' . esc_attr( get_option('woocommerce_weight_unit' ) );
		else print 'N/A';
	}
}




/* E-mail verificatie voor Contact Form 7 plugin.
*/
add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );
  
function custom_email_confirmation_validation_filter( $result, $tag ) {
  if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';
  
    if ( $your_email != $your_email_confirm ) {
      $result->invalidate( $tag, "De ingevulde e-mailadressen komen niet overeen." );
    }
  }
  
  return $result;
}