<?php
//remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_show_product_loop_sale_flash', 10 ); 
//remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 10 );
//
//add_filter( 'woocommerce_sale_flash', 'bbloomer_rename_sale_badge', 9999 );
// 
//function bbloomer_rename_sale_badge() {
//   return '<span class="sales-badge onsale">ON OFFER</span>';
//}

// add_filter('woocommerce_sale_flash', 'my_custom_sales_badge');
function my_custom_sales_badge() {
    $img = '<img class="sales-badge onsale" src="http://localhost/vega/wp-content/uploads/sale1.png" style="width:20%;" ></img>';
    return $img;
}


//add_filter( 'woocommerce_sale_flash', 'misha_remove_on_sale_badge' );
// 
//function misha_remove_on_sale_badge( $badge_html ){
//	return '';
//}

//add_filter( 'woocommerce_sale_flash', 'misha_change_on_sale_badge', 10, 2 );
// 
//function misha_change_on_sale_badge( $badge_html, $post ) {
//	return '<span class="onsale">Top!</span>';
//}

// order status change custom actions
// add_action('woocommerce_order_status_changed', 'order_status_change_custom_actions', 20, 4 );
function order_status_change_custom_actions( $order_id, $old_status, $new_status, $order ){
	
	$os = get_post_meta( $order_id, '_os', true );
	if(empty($os))
			add_post_meta($order_id, '_os', $old_status." -> ".$new_status);
		else
			update_post_meta($order_id, '_os', $old_status." -> ".$new_status);
	
    if ($old_status = "on-hold" and $new_status == 'processing' ) {
		// do nothing
    }elseif ($old_status == "pending" and $new_status == 'processing' ) {		
		// send push notificaiton
		// send SMS
    }elseif ($new_status == 'shipped' ) {
		//if(empty($fa))
		//	add_post_meta($order_id, 'sms', 'sms shipped');
		//else
		//	update_post_meta($order_id, '_fa', $isnewtrans);
		    	
    }
}




// display item detail on fronaccounting
// add_filter( 'manage_product_posts_custom_column', 'wpso23858236_product_column_offercode', 10, 3);
function wpso23858236_product_column_offercode( $column, $postid ) {
	global $product;
    if ( $column == 'sku' ) {
		$sku = $product->get_sku();
		if ($sku){?>
	<a href="<?php echo site_url();?>/fa/inventory/manage/items.php?stock_id=<?php echo $product->get_sku();?>" target="new">FA Detail</a>
	<br>
	<?php
		}
	}
}


// Add Product Video Tab on Single Product Page
// add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );
function woo_custom_product_tabs( $tabs ) {
// https://stackoverflow.com/questions/39964939/adding-multiple-tabs-to-woocommerce-single-product-pages
	global $post;  
	$pv = get_post_meta( $post->ID , 'product_video', true );
	if(!empty($pv)){
    $tabs['product_video'] = array(
        'title'     => __( 'Product Video', 'woocommerce' ),
        'priority'  => 1,
        'callback'  => 'product_video_content'
    );
	}	
    return $tabs;

}
// Product Video Contents
function product_video_content() {
	global $post;
	?>
	<iframe width="100%" height="315" src="https://www.youtube.com/embed/<?php echo get_post_meta( $post->ID , 'product_video', true );?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
	<?php
}



// disbale unique SKU for products
// add_filter( 'wc_product_has_unique_sku', '__return_false' ); 

// set width of CN# column orders list
add_action('admin_head', 'my_column_width');
function my_column_width() {
    echo '<style type="text/css">';
    echo '.column-my-column1 { text-align: center; width:175px !important; overflow:hidden; }';
    echo '</style>';
	
	echo '<style type="text/css">';
    echo '.column-fa-column { text-align: center;}';
    echo '</style>';
}


// add js file for CN#
// add_action('admin_enqueue_scripts', 'tutsplus_enqueue_custom_js');
function tutsplus_enqueue_custom_js() {	
	wp_enqueue_script('custom', get_stylesheet_directory_uri().'/js/cn.js');
	$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri(),'siteUrl' => site_url() );
	wp_localize_script( 'custom', 'object_name', $translation_array );
	
	wp_enqueue_script('fa', get_stylesheet_directory_uri().'/js/fa.js');
	$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri(),'siteUrl' => site_url() );
	wp_localize_script( 'fa', 'fa_object', $translation_array );
}

// return / exchanghe form download link
function returnexchangeform() { 
	$file = get_field('return_exchange_form','option');
	if( $file ):
		$url = wp_get_attachment_url( $file );
		$file = "<a href=".esc_html($url)."?".rand()." target='new'>".get_field('return_exchange_caption','option')."</a>";	
		endif;

	// Output needs to be return
	return $file;
} 
// register shortcode
// add_shortcode('return-exchange-form', 'returnexchangeform'); 


// add_action( 'woocommerce_before_single_product', 'cosmetics_model', 10 );
// add_action( 'woocommerce_before_single_product_summary', 'cosmetics_model', 10 );
//add_action( 'woocommerce_before_single_product_summary', 'cosmetics_model', 20 );
// add_action( 'woocommerce_product_thumbnails', 'cosmetics_model', 20 );

function cosmetics_model(){	
	global $product;
//	$term_list = wp_get_post_terms($product->post->ID , 'product_cat', array('fields' => 'ids'));
//	$term_list = wp_get_post_terms($product->post->ID , 'product_cat', array('fields' => 'names'));
//	print_r ($term_list);
	$image = get_field('product_model_image');
	$size = 'full'; // (thumbnail, medium, large, full or custom size)
	if( $image ) {
		echo wp_get_attachment_image( $image, $size );
	}
	
}

/**
 * WooCommerce, Add Short Description to Products on Shop Page
 *
 * @link https://wpbeaches.com/woocommerce-add-short-or-long-description-to-products-on-shop-page
 */
// add_action( 'woocommerce_after_shop_loop_item_title', 'wc_add_short_description' );
function wc_add_short_description() {
	global $product;
	?>
        <div id="shortdescription" itemprop="description">
            <?php echo apply_filters( 'woocommerce_short_description', $product->post-> post_excerpt ) ?>
        </div>
	<?php
}


// inherit default style sheet from parent theme


// wp_enqueue_script( 'jquery' );

// Remove the WordPress default jquery
// wp_deregister_script( 'jquery' );

// set jquery using a local file
 //wp_enqueue_script( 'jquery', get_stylesheet_directory_uri() . '/jquery-1.10.2/jquery.min.js');

// using jquery google CDN
// wp_enqueue_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', '', '3.3.1', true);

function frontEnd_scripts() {
    wp_enqueue_script("jquery");
    wp_deregister_script('jquery.mobile');
    wp_register_script('jquery.mobile', ("//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.js"),array('jquery'));
    wp_enqueue_script('jquery.mobile');
    wp_register_style('jqm_css',('//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css'));
    wp_enqueue_style('jqm_css');
}
// add_action('wp_enqueue_scripts', 'frontEnd_scripts'); 

// heading before cart table
add_action( 'woocommerce_before_cart_table', 'heading_before_cart_table', 9, 4 );	
function heading_before_cart_table(){
	echo "<h4>Cart Product(s)</h4>";
}


// ADDING 2 NEW COLUMNS WITH THEIR TITLES (keeping "Total" and "Actions" columns at the end)
// add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column', 20 );
function custom_shop_order_column($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['fa-column'] = __( 'FA #','theme_domain');
            $reordered_columns['my-column1'] = __( 'MNP/CC/SL #','theme_domain');
//        	$reordered_columns['my-column2'] = __( 'MNP/CC','theme_domain');

        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for each new column (example)
// add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );

function custom_orders_list_column_content( $column, $post_id )
{
	global $post;
    switch ( $column )
    {
    case 'fa-column' :
    	$order = new WC_Order( $post );		
    //	echo $order->get_status()."<br />";
    	$shipment_tracking_items = get_post_meta( $post_id, '_wc_shipment_tracking_items', true );
    	$fa = get_post_meta( $post_id, '_fa', true );
    	if (!empty($shipment_tracking_items) and ($order->get_status()=="shipped" or $order->get_status()=="delivered" or $order->get_status()=="completed")  ){				
    		?>
    		<div id="fasr<?php echo $post->ID; ?>">
    		<?php
    		if(!empty($fa)){?>
    			<a title="View Sales Order" href="<?php echo site_url();?>/fa/sales/view/view_sales_order.php?trans_no=<?php echo $fa;?>&trans_type=30" target="new" >FA #<?php echo $fa;?></a><br>
    			<a title="View Sales Invocie" href="<?php echo site_url();?>/fa/sales/view/view_invoice.php?trans_no=<?php echo $fa;?>&trans_type=10" target="new">Invoice</a> /
    			<a title="Sales Invoice GL" href="<?php echo site_url();?>/fa/gl/view/gl_trans_view.php?type_id=10&trans_no=<?php echo $fa;?>" target="new">GL</a><br>
    			<a title="View Dispatch Note" href="<?php echo site_url();?>/fa/sales/view/view_dispatch.php?trans_no=<?php echo $fa;?>&trans_type=13" target="new" >Dispatch</a> /
    			<a title="Delivery Note GL" href="<?php echo site_url();?>/fa/gl/view/gl_trans_view.php?type_id=13&trans_no=<?php echo $fa;?>" target="new">GL</a><br>
    			<a title="Edit Sales Order Invoice" href="<?php echo site_url();?>/fa/sales/customer_invoice.php?ModifyInvoice=<?php echo $fa;?>" target="new">Edit Invoice</a>  |        
    		    <a onClick="javascript:delfa(<?php echo $post->ID; ?>,<?php echo $fa; ?>);">Del</a>       
    		<?php } else{?>					
    			<a onClick="javascript:fa(<?php echo $post->ID; ?>);">FA #</a>					
    		<?php } ?>
    		</div>
    	<?php
    	} elseif (!empty($shipment_tracking_items) and (!empty($fa)) and ($order->get_status()=="cancelled" or $order->get_status()=="refunded")  ){ ?>
    	<div id="fasr<?php echo $post->ID; ?>">
    		<a title="View Sales Order" href="<?php echo site_url();?>/fa/sales/view/view_sales_order.php?trans_no=<?php echo $fa;?>&trans_type=30" target="new" >FA #<?php echo $fa;?></a><br>
    		<a title="View Sales Invocie" href="<?php echo site_url();?>/fa/sales/view/view_invoice.php?trans_no=<?php echo $fa;?>&trans_type=10" target="new">Invoice</a> /
    		<a title="Sales Invoice GL" href="<?php echo site_url();?>/fa/gl/view/gl_trans_view.php?type_id=10&trans_no=<?php echo $fa;?>" target="new">GL</a><br>
    		<a title="View Dispatch Note" href="<?php echo site_url();?>/fa/sales/view/view_dispatch.php?trans_no=<?php echo $fa;?>&trans_type=13" target="new" >Dispatch</a> /
    		<a title="Delivery Note GL" href="<?php echo site_url();?>/fa/gl/view/gl_trans_view.php?type_id=13&trans_no=<?php echo $fa;?>" target="new">GL</a><br>
    		<a title="Edit Sales Order Invoice" href="<?php echo site_url();?>/fa/sales/customer_invoice.php?ModifyInvoice=<?php echo $fa;?>" target="new">Edit</a> |        
    		<a onClick="javascript:delfa(<?php echo $post->ID; ?>,<?php echo $fa; ?>);">Del</a>
    	</div>
    	<?php
    	}else{?>
    	-
    		<?php /*?><a onClick="javascript:fa(<?php echo $post->ID; ?>);">FA #</a><?php */?>
    	<?php
    	}
    //			echo "<br />";
    //			$trans_id = ifexists("0_", $post_id);			
    //
    //			if ( $trans_id > 0){
    //			$fa = get_post_meta( $post_id , '_fa', true );
    //			if(empty($fa))
    //	    		add_post_meta($post_id, '_fa', $trans_id);
    //			else
    //	    		update_post_meta($post_id, '_fa', $trans_id);
    
    	?>
    <?php /*?>			<a href="<?php echo site_url();?>/fa/sales/view/view_invoice.php?trans_no=<?php echo $trans_id;?>&trans_type=10" target="new"><?php echo $trans_id;?></a><?php } ?>
    <?php */?>
    	<?php
    	break;
        case 'my-column1' :
			
			// MNP CN //
            $mnpcn = get_post_meta( $post_id, '_mnpcn', true );
			?>
			<div id="mnpsr<?php echo $post->ID; ?>">
			<?php
            if(!empty($mnpcn)){?>
				<a href="<?php site_url()?>/mnpt/?cn=<?php echo $mnpcn;?>" target="new"><?php echo $mnpcn;?></a>            
            <?php } else {?>
				<a onClick="javascript:mnpcn(<?php echo $post->ID; ?>);">MNPCN</a>
				
			<?php } ?>
				
			<?php
			$mnpcnres = get_post_meta( $post_id, '_mnpcnres', true );
            if(!empty($mnpcnres)){?>
				| <a onClick="javascript:mnpcnres(<?php echo $post->ID; ?>);">Log</a>	
			<?php } ?>				
			</div>
			
			<?php
			// Call Courier CN //
            $cccn = get_post_meta( $post_id, '_cccn', true );
			?>
			<div id="ccsr<?php echo $post->ID; ?>">
			<?php
            if(!empty($cccn)){
				$tracking_url = get_field('callcourier_tracking_url', 'option');
				?>
				<a href="<?php echo $tracking_url; ?><?php echo $cccn;?>" target="new"><?php echo $cccn;?></a>            
            <?php } else {?>
				<a onClick="javascript:cccn(<?php echo $post->ID; ?>);">CCCN</a>
			<?php } ?>
				
			<?php
			$cccnres = get_post_meta( $post_id, '_cccnres', true );
            if(!empty($cccnres)){?>
				| <a onClick="javascript:cccnres(<?php echo $post->ID; ?>);">Log</a>	
			<?php } ?>				

			</div>


			<?php
			// Swyft Logisgice CN //
            $slcn = get_post_meta( $post_id, '_slcn', true );
			?>
			<div id="slsr<?php echo $post->ID; ?>">
			<?php
            if(!empty($slcn)){
				$tracking_url = get_field('swyft-logistics_tracking_url', 'option');
				?>			
				<a href="<?php echo $tracking_url; ?><?php echo $slcn;?>" target="new"><?php echo $slcn;?></a> 
            <?php } else {?>
				<a onClick="javascript:slcn(<?php echo $post->ID; ?>);">SLCN</a>
			<?php } ?>
				
			<?php
			$slcnres = get_post_meta( $post_id, '_slcnres', true );
            if(!empty($slcnres)){?>
				| <a onClick="javascript:slcnres(<?php echo $post->ID; ?>);">Log</a>	
			<?php } ?>	
			</div>

			<?php
            break;

        case 'my-column2' :
            ?>
			<a href="<?php echo site_url();?>/mnpcn/?cn=<?php echo $post->ID; ?>" target="new">MNP#</a> / 
			<a href="<?php echo site_url();?>/cccn/?cn=<?php echo $post->ID; ?>" target="new">CC#</a>
			
			<?php
            break;
    }
}


// display before single product page	
add_action( 'woocommerce_before_single_product', 'display_banner_woocommerce_before_shop_loop', 9, 4 );	
// display after single product page
add_action( 'woocommerce_after_single_product', 'display_banner_woocommerce_after_shop_loop', 9, 4 );	

// display before shop page loop	
add_action( 'woocommerce_before_shop_loop', 'display_banner_woocommerce_before_shop_loop', 9, 4 );	
function display_banner_woocommerce_before_shop_loop(){
	echo get_field("contents_before_shop_loop","option");
}
// display after shop page loop
add_action( 'woocommerce_after_shop_loop', 'display_banner_woocommerce_after_shop_loop', 9, 4 );	
function display_banner_woocommerce_after_shop_loop(){
	echo get_field("contents_after_shop_loop","option");
}


// remove payment instructions from completed order email
add_action( 'woocommerce_email_before_order_table', 'action_email_before_order_table_callback', 9, 4 );
function action_email_before_order_table_callback( $order, $sent_to_admin, $plain_text, $email ){
    $payment_method = $order->get_payment_method();

    // Targeting "COD" payment method on Customer completed order email notification
    if ( ('customer_note' === $email->id or 'customer_completed_order' === $email->id or 'customer_refunded_order' === $email->id) && 'cod' === $payment_method ) {
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
        remove_action( 'woocommerce_email_before_order_table', [ $available_gateways[$payment_method], 'email_instructions' ], 10 );
    }
}


// more products on single page
add_action( 'woocommerce_after_single_product', 'action_function_name_8927' );
add_action( 'woocommerce_after_single_product_summary', 'action_function_name_8927' );
function action_function_name_8927(){
$shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
echo "<div class='moreproducts'><a href='".$shop_page_url."'> >> More products...</a></div>";
}


// Update WooCommerce Flexslider options

add_filter( 'woocommerce_single_product_carousel_options', 'ud_update_woo_flexslider_options' );

function ud_update_woo_flexslider_options( $options ) {

	// show arrows
      $options['directionNav'] = true;
//      $options['animation'] = "slide";
//
//      // infinite loop
//      $options['animationLoop'] = true;
//
//      // autoplay (work with only slideshow too)
//      $options['slideshow'] = true;
//      //$options['autoplay'] = true;
//
//      // control par texte (boolean) ou bien par vignettes
//      $options['controlNav'] = true;
//      $options['controlNav'] = "thumbnails";
//
//      $options['mousewheel'] = true;

    return $options;
}





/**
 * @snippet       Add Content to the Customer Processing Order Email - WooCommerce
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
add_action( 'woocommerce_email_before_order_table', 'add_content_specific_email_before_table', 20, 4 );
  function add_content_specific_email_before_table( $order, $sent_to_admin, $plain_text, $email ) {
	echo get_field("all_emails_contents_before_order_table","option");
   	if ( $email->id == 'new_order' ) {
    	echo get_field("admin_new_order_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_processing_order' ) {
    	echo get_field("customer_processing_order_contents_before_order_table","option");
   	}
   	if ( $email->id == 'cancelled_order' ) {
    	echo get_field("customer_cencelled_order_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_completed_order' ) {
    	echo get_field("customer_completed_order_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_invoice' ) {
    	echo get_field("customer_invoice_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_new_account' ) {
    	echo get_field("customer_new_account_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_note' ) {
    	echo get_field("customer_note_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_on_hold_order' ) {
    	echo get_field("customer_on_hold_order_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_refunded_order' ) {
    	echo get_field("customer_refunded_order_contents_before_order_table","option");
   	}
   	if ( $email->id == 'customer_reset_password' ) {
    	echo get_field("customer_reset_pasword_contents_before_order_table","option");
   	}
   	if ( $email->id == 'failed_order' ) {
    	echo get_field("customer_failed_order_contents_before_order_table","option");
   	}
}

add_action( 'woocommerce_email_after_order_table', 'add_content_specific_email_after_table', 20, 4 );
  function add_content_specific_email_after_table( $order, $sent_to_admin, $plain_text, $email ) {

      	if ( $email->id == 'new_order' ) {
    	echo get_field("admin_new_order_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_processing_order' ) {
    	echo get_field("customer_processing_order_contents_after_order_table","option");
   	}
   	if ( $email->id == 'cancelled_order' ) {
    	echo get_field("customer_cencelled_order_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_completed_order' ) {
    	echo get_field("customer_completed_order_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_invoice' ) {
    	echo get_field("customer_invoice_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_new_account' ) {
    	echo get_field("customer_new_account_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_note' ) {
    	echo get_field("customer_note_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_on_hold_order' ) {
    	echo get_field("customer_on_hold_order_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_refunded_order' ) {
    	echo get_field("customer_refunded_order_contents_after_order_table","option");
   	}
   	if ( $email->id == 'customer_reset_password' ) {
    	echo get_field("customer_reset_pasword_contents_after_order_table","option");
   	}
   	if ( $email->id == 'failed_order' ) {
    	echo get_field("customer_failed_order_contents_after_order_table","option");
   	}
	  echo get_field("all_emails_contents_after_order_table","option");

}


if( function_exists('acf_add_options_page') ) {
	
	acf_add_options_page(array(
		'page_title' 	=> 'Email Contents',
		'menu_title'	=> 'Email Contents',
		'menu_slug' 	=> 'email-contents',
		'capability'	=> 'edit_posts',
		'redirect'		=> false
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Admin new order',
		'menu_title'	=> 'Admin new order',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer processing order',
		'menu_title'	=> 'Customer processing order',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer on hold order',
		'menu_title'	=> 'Customer on hold order',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer completed order',
		'menu_title'	=> 'Customer completed order',
		'parent_slug'	=> 'email-contents',
	));
		acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer cancelled order',
		'menu_title'	=> 'Customer cancelled order',
		'parent_slug'	=> 'email-contents',
	));	
		acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer refunded order',
		'menu_title'	=> 'Customer refunded order',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer failed order',
		'menu_title'	=> 'Custoemr faild order',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer invoice',
		'menu_title'	=> 'Customer invoice',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer new account',
		'menu_title'	=> 'Customer new account',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer note',
		'menu_title'	=> 'Customer note',
		'parent_slug'	=> 'email-contents',
	));	
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Customer reset password',
		'menu_title'	=> 'Customer reset password',
		'parent_slug'	=> 'email-contents',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'All emails',
		'menu_title'	=> 'All emails',
		'parent_slug'	=> 'email-contents',
	));

}

// Targets custom order status "refused"
// Uses 'woocommerce_order_status_' hook
  
add_action( 'woocommerce_order_status_shipped', 'order_status_notification', 20, 2 ); 
function order_status_notification( $order_id, $order ) {
      
//    $heading = 'Order Shipped';
 //   $subject = 'Order Shipped';
	$heading   = __('Your Order #{order_number} has been shipped','woocommerce');
    $subject   = 'Your {site_title} Order #{order_number} is now shipped';

  
    // Get WooCommerce email objects
    $mailer = WC()->mailer()->get_emails();
  
    // Use one of the active emails e.g. "Customer_Completed_Order"
    // Wont work if you choose an object that is not active
    // Assign heading & subject to chosen object
    $mailer['WC_Email_Customer_Completed_Order']->heading = $heading;
    $mailer['WC_Email_Customer_Completed_Order']->settings['heading'] = $heading;
    $mailer['WC_Email_Customer_Completed_Order']->subject = $subject;
    $mailer['WC_Email_Customer_Completed_Order']->settings['subject'] = $subject;
  
    // Send the email with custom heading & subject
    $mailer['WC_Email_Customer_Completed_Order']->trigger( $order_id ); 
    // To add email content use https://businessbloomer.com/woocommerce-add-extra-content-order-email/
    // You have to use the email ID chosen above and also that $order->get_status() == "refused"
      
}

// https://wisdmlabs.com/blog/add-shipped-order-status-woocommerce/
// Register a custom order status
add_action('init', 'register_custom_order_statuses');
function register_custom_order_statuses() {
    register_post_status('wc-shipped ', array(
        'label' => __( 'Shipped', 'woocommerce' ),
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true,
        'label_count' => _n_noop('Shipped <span class="count">(%s)</span>', 'Shipped <span class="count">(%s)</span>')
    ));
}


// Add a custom order status to list of WC Order statuses
add_filter('wc_order_statuses', 'add_custom_order_statuses');
function add_custom_order_statuses($order_statuses) {
    $new_order_statuses = array();

    // add new order status before processing
    foreach ($order_statuses as $key => $status) {
        $new_order_statuses[$key] = $status;
        if ('wc-on-hold' === $key) {
            $new_order_statuses['wc-shipped'] = __('Shipped', 'woocommerce' );
        }
    }
    return $new_order_statuses;
}


// Adding custom status to admin order list bulk dropdown
add_filter( 'bulk_actions-edit-shop_order', 'custom_dropdown_bulk_actions_shop_order', 50, 1 );
function custom_dropdown_bulk_actions_shop_order( $actions ) {
    $new_actions = array();

    // add new order status before processing
    foreach ($actions as $key => $action) {
        if ('mark_processing' === $key)
            $new_actions['mark_shipped'] = __( 'Change status to shipped', 'woocommerce' );

        $new_actions[$key] = $action;
    }
    return $new_actions;
}

// Add a custom order status action button (for orders with "processing" status)
add_filter( 'woocommerce_admin_order_actions', 'add_custom_order_status_actions_button', 100, 2 );
function add_custom_order_status_actions_button( $actions, $order ) {
    // Display the button for all orders that have a 'processing', 'pending' or 'on-hold' status
    if ( $order->has_status( array( 'on-hold', 'processing', 'pending' ) ) ) {

        // The key slug defined for your action button
        $action_slug = 'shipped';

        // Set the action button
        $actions[$action_slug] = array(
            'url'       => wp_nonce_url( admin_url( 'admin-ajax.php?action=woocommerce_mark_order_status&status='.$action_slug.'&order_id='.$order->get_id() ), 'woocommerce-mark-order-status' ),
            'name'      => __( 'Shipped', 'woocommerce' ),
            'action'    => $action_slug,
        );
    }
    return $actions;
}

// Set styling for custom order status action button icon and List icon
add_action( 'admin_head', 'add_custom_order_status_actions_button_css' );
function add_custom_order_status_actions_button_css() {
    $action_slug = "shipped"; // The key slug defined for your action button
    ?>
    <style>
        .wc-action-button-<?php echo $action_slug; ?>::after {
            font-family: woocommerce !important; content: "\e029" !important;
        }
    </style>
    <?php
}


// set global variables
 function test() {
        global $no_category_page_content;;
        $no_category_page_content = 'hello world';
    }
add_action( 'after_setup_theme', 'test' );

// setup option pages
if( function_exists('acf_add_options_page') ) {
	
	acf_add_options_page(array(
		'page_title' 	=> 'Website Options',
		'menu_title'	=> 'Website Options',
		'menu_slug' 	=> 'website-options',
		'capability'	=> 'edit_posts',
		'redirect'		=> false
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Empty Category Contents',
		'menu_title'	=> 'Empty Category',
		'parent_slug'	=> 'website-options',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Shop/Product Page Contents',
		'menu_title'	=> 'Shop/Product Page',
		'parent_slug'	=> 'website-options',
	));

	acf_add_options_sub_page(array(
		'page_title' 	=> 'Invocie Contents',
		'menu_title'	=> 'Invoice Contents',
		'parent_slug'	=> 'website-options',
	));
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Packing List Contents',
		'menu_title'	=> 'Packing List Contents',
		'parent_slug'	=> 'website-options',
	));

}

// Display Product Short Description in WooCommerce Checkout
// add_filter( 'woocommerce_get_item_data', 'wc_checkout_description_so_15127954', 10, 2 );
function wc_checkout_description_so_15127954( $other_data, $cart_item )
{
    $post_data = get_post( $cart_item['product_id'] );
    $other_data[] = array( 'name' =>  $post_data->post_excerpt );    
    return $other_data;
}


// Show Amount Left for Free Shipping on Checkout Page
// add_action( 'woocommerce_before_checkout_form', 'wc_add_notice_free_shipping' );

// Show Amount Left for Free Shipping on Cart Page
// add_action( 'woocommerce_before_cart', 'wc_add_notice_free_shipping' );

function wc_add_notice_free_shipping() {

           $amount_for_free_shipping = get_free_shipping_minimum( 'Pakistan' );
           $cart = WC()->cart->subtotal;
           $remaining = $amount_for_free_shipping - $cart;
          if ( $cart == 0 ){
            $notice = "Free shipping for orders over Rs. ".$amount_for_free_shipping;
            wc_print_notice( $notice , 'notice' );}
          elseif( $cart >= $amount_for_free_shipping ){
            $notice = "Congratulations! You've got free shipping";
            wc_print_notice( $notice , 'notice' );
          }else{
            $notice = "Only Rs ".$remaining." away from free shipping";
            wc_print_notice( $notice , 'notice' );
          }
}

// add shortcode fof free shipping
// add_shortcode('notice_free_shipping', 'top_add_notice_free_shipping'); 
// Show Amount Left for Free Shipping on Top Header
function top_add_notice_free_shipping() {

           $amount_for_free_shipping = get_free_shipping_minimum( 'Pakistan' );
           $cart = WC()->cart->subtotal;
           $remaining = $amount_for_free_shipping - $cart;
          if ( $cart == 0 ){
            	$notice = "Free shipping for orders over Rs. ".$amount_for_free_shipping;}
          elseif( $cart >= $amount_for_free_shipping ){
            	$notice = "Congratulations! You've got free shipping";}
          else{
            $notice = "Only Rs ".$remaining." away from free shipping";
          }
		 echo $notice = "<div class='freeshippingmsg animate bounceIn'>".$notice."</div>";
}

/**
 * Accepts a zone name and returns its threshold for free shipping.
 *
 * @param $zone_name The name of the zone to get the threshold of. Case-sensitive.
 * @return int The threshold corresponding to the zone, if there is any. If there is no such zone, or no free shipping method, null will be returned.
 */
function get_free_shipping_minimum($zone_name = 'Pakistan') {
  if ( ! isset( $zone_name ) ) return null;

  $result = null;
  $zone = null;

  $zones = WC_Shipping_Zones::get_zones();
  foreach ( $zones as $z ) {
    if ( $z['zone_name'] == $zone_name ) {
      $zone = $z;
    }
  }

  if ( $zone ) {
    $shipping_methods_nl = $zone['shipping_methods'];
    $free_shipping_method = null;
    foreach ( $shipping_methods_nl as $method ) {
      if ( $method->id == 'free_shipping' ) {
        $free_shipping_method = $method;
        break;
      }
    }

    if ( $free_shipping_method ) {
      $result = $free_shipping_method->min_amount;
    }
  }

  return $result;
}


/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 */


function my_hide_shipping_when_free_is_available( $rates ) {
	$free = array();

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


// Remove WooCommerce SKUs Only on Product Pages
// add_filter( 'wc_product_sku_enabled', 'sv_remove_product_page_skus' );
function sv_remove_product_page_skus( $enabled ) {
    if ( ! is_admin() && is_product() ) {
        return false;
    }
    return $enabled;
}


/* after an order has been processed, we will use the  'woocommerce_thankyou' hook, to add our function, to send the data */
// add_action('woocommerce_thankyou', 'wdm_send_order_to_ext');
function wdm_send_order_to_ext( $order_id ){

 }

function searchForDestCityId($DestCityName){
    
    $url= "http://cod.callcourier.com.pk/API/CallCourier/GetCityListByService?serviceID=7";
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $citylist = curl_exec($ch);
    curl_close($ch);

   $citylist = json_decode($citylist);
    $DestCityId = 0;
	for($i = 0; $i < count($citylist); $i++) {
		foreach ($citylist[$i] as $key => $value) {
			// echo $key." : ".$value;
			if ($key=="CityID"){$DestCityId = $value;}
			if ($key=="CityName") {$DestCityName1 = $value;}
		//	echo "<br />";
		}
		if ($DestCityName1 === $DestCityName){
			return $DestCityId;
		}
	}
   return null;
}


function searchForDestCityId11($DestCityName){
	$DestCityName = strtoupper($DestCityName);
	$url= "http://cod.callcourier.com.pk/API/CallCourier/GetCityListByService?serviceID=7";
	$url =  str_replace(' ', '%20', $url);
	$response = file_get_contents($url);
	$response = json_decode($response);
	$DestCityId = 0;
	for($i = 0; $i < count($response); $i++) {
		foreach ($response[$i] as $key => $value) {
			// echo $key." : ".$value;
			if ($key=="CityID"){$DestCityId = $value;}
			if ($key=="CityName") {$DestCityName1 = $value;}
		//	echo "<br />";
		}
		if ($DestCityName1 === $DestCityName){
			return $DestCityId;
		}
	}
   return null;
}

/**
 * Replace XX with the country code. Instead of YYY, ZZZ use actual state codes.
 * The City list can list of city name with postcode or just city name.
 */

add_filter( 'ry_wc_city_select_cities', 'checkout_cities' );
function checkout_cities( $cities ) {
	$city_names_option = get_field("city_names","option");
	$city_names[] = explode("\n",$city_names_option);
	$cities['PK'] =  $city_names[0];
	
	return $cities;
}


// add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields1' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields1( $fields ) {
     $fields['shipping']['shipping_phone'] = array(
    'label'     => __('Phone', 'woocommerce'),
    'placeholder'   => _x('Phone', 'placeholder', 'woocommerce'),
    'required'  => true,
    'class'     => array('form-row-wide'),
    'clear'     => true
     );

     return $fields;
}


// Place holder for Billing Phone on checkout
//add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
     $fields['billing']['billing_phone']['placeholder'] = '03xxxxxxxxx';
     return $fields;
}

// Custom validation for Billing Phone checkout field
// add_action('woocommerce_checkout_process', 'custom_validate_billing_phone');

function custom_validate_billing_phone() {
    $is_correct = preg_match('/^03[0-9]{9}$/', $_POST['billing_phone']);
    if ( $_POST['billing_phone'] && !$is_correct) {
        wc_add_notice( __( '<strong>Invalid Phone Number </strong> The Phone field should be : 03xxxxxxxxx' ), 'error' );
    }
}

// Disable FATA state for Pakistan
add_filter( 'woocommerce_states', 'custom_us_states', 10, 1 );
function custom_us_states( $states ) {
    $non_allowed_us_states = array( 'TA');

    // Loop through your non allowed us states and remove them
    foreach( $non_allowed_us_states as $state_code ) {
        if( isset($states['PK'][$state_code]) )
            unset( $states['PK'][$state_code] );
    }
    return $states;
}



// add_action('wp_footer', 'format_checkout_billing_phone');
function format_checkout_billing_phone() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('#billing_phone').on( 'input focusout', function() {
            var p = $(this).val();
            p = p.replace(/[^0-9]/g, '');
            p = p.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
            $(this).val(p);
        });
    });
    </script>
    <?php
    endif;
}


// buy now button at single product page START
function buy_now_submit_form() {
 ?>
  <script>
      jQuery(document).ready(function(){
          // listen if someone clicks 'Buy Now' button
          jQuery('#buy_now_button').click(function(){
              // set value to 1
              jQuery('#is_buy_now').val('1');
              //submit the form
              jQuery('form.cart').submit();
          });
      });
  </script>
 <?php
}
add_action('woocommerce_after_add_to_cart_form', 'buy_now_submit_form');


add_filter('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($redirect_url) {
  if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) {
     global $woocommerce;
     $redirect_url = wc_get_checkout_url();
  }
  return $redirect_url;
}
// buy now button at single product page END


/*Remove WordPress menu from admin bar*/
add_action( 'admin_bar_menu', 'remove_wp_logo', 999 );
function remove_wp_logo( $wp_admin_bar ) {
	$wp_admin_bar->remove_node( 'wp-logo' );
}

// Change WordPress Logo on Signup Page:
function my_login_logo_one() { 
?> 
<style type="text/css"> 
body.login div#login h1 a {
 background-image: url(https://www.vega.pk/wp-content/uploads/v-logo-280.png);
padding-bottom: 30px; 
} 
</style>
 <?php 
} add_action( 'login_enqueue_scripts', 'my_login_logo_one' );

// Changing the Logo URL
add_filter( 'login_headerurl', 'custom_loginlogo_url' );

function custom_loginlogo_url($url) {

     return site_url();

}

// add_filter('rtwpvg_get_image_props', function ($props){
//    if(isset($props['archive_class']))
//        unset($props['archive_class']);
//    if(isset($props['archive_src_h']))
//        unset($props['archive_src_h']);
//    if(isset($props['archive_src_h']))
//        unset($props['archive_src_w']);
//    if(isset($props['caption']))
//        unset($props['caption']);
//    if(isset($props['class']))
//        unset($props['class']);
//    if(isset($props['full_class']))
//        unset($props['full_class']);
//    if(isset($props['gallery_thumbnail_class']))
//        unset($props['gallery_thumbnail_class']);
//    if(isset($props['srcset']))
//        unset($props['srcset']);
//    if(isset($props['title']))
//        unset($props['title']);
    
//    return $props;
//});



// White lable muffin editor at admin area
// define( 'WHITE_LABEL', true );