<?php

add_action('woocommerce_order_status_changed', 'custom_status_email_notifications', 20, 4 );
function custom_status_email_notifications( $order_id, $old_status, $new_status, $order ){
    if ($new_status == 'processing' ) {
		//if(empty($fa))
			add_post_meta($order_id, 'sms', 'sms processing');
		//else
		//	update_post_meta($order_id, '_fa', $isnewtrans);
		
    	//echo "THIS IS TEST THIS IS TEST";
    }elseif ($new_status == 'shipped' ) {
		//if(empty($fa))
			add_post_meta($order_id, 'sms', 'sms shipped');
		//else
		//	update_post_meta($order_id, '_fa', $isnewtrans);
		
    	//echo "THIS IS TEST THIS IS TEST";
    }
}



// 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="400" src="https://www.youtube.com/embed/<?php echo get_post_meta( $post->ID , 'product_video', true );?>?loop=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
	<?php	
}
//function woo_qty_pricing_tab_content() {
//    // The qty pricing tab content
//    echo '<h2>Quantity Pricing</h2>';
//    echo '<p>Here\'s your quantity pricing tab.</p>';
//}
//function woo_other_products_tab_content() {
//    // The other products tab content
//    echo '<h2>Other Products</h2>';
//    echo '<p>Here\'s your other products tab.</p>';
//}


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

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>';
}


/* Custom script with no dependencies, enqueued in the header */
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 );
}


/**
 * Generated by the WordPress Option Page generator
 * at http://jeremyhixon.com/wp-tools/option-page/
 */

// 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="https://www.vega.pk/mnpt.php?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)){?>
				<a href="https://callcourier.com.pk/tracking/?tc=<?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)){?>				
				<a href="http://parceltracking.swyftlogistics.com/?<?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;
    }
}


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 that runs when shortcode is called

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 );
	}
	
}

function get_product_category_by_id( $category_id ) {
    $term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
    return $term['name'];
}

add_action( 'woocommerce_after_shop_loop_item_title', 'wc_add_short_description' );
/**
 * WooCommerce, Add Short Description to Products on Shop Page
 *
 * @link https://wpbeaches.com/woocommerce-add-short-or-long-description-to-products-on-shop-page
 */
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
}

add_filter( 'woocommerce_package_rates', 'bbloomer_woocommerce_tiered_shipping', 9999, 2 );    
function bbloomer_woocommerce_tiered_shipping( $rates, $package ) {
     echo "Weight: ".WC()->cart->get_cart_contents_weight()." KG";
	
     if ( WC()->cart->get_cart_contents_weight() <= 1.0 ) {
       
         if ( isset( $rates['flat_rate:5'] ) ) unset( $rates['flat_rate:6'], $rates['flat_rate:1'] );
       
     } elseif ( WC()->cart->get_cart_contents_weight() <= 2.0 ) {
       
        if ( isset( $rates['flat_rate:1'] ) ) unset( $rates['flat_rate:1'], $rates['flat_rate:7'] );
       
     }
	// else {
       
     //    if ( isset( $rates['flat_rate:5'] ) ) unset( $rates['flat_rate:5'], $rates['flat_rate:6'] );
       
    // }
    
     return $rates;
    
}


function db(){
	static $conn;

	$servername = "127.0.0.1";
	$username = "root";
	$password = "amersaeed";
	$dbname = "frontaccounting";

	if ($conn===NULL){
        $conn = new mysqli($servername, $username, $password, $dbname);
    }
return $conn;

}

// add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );

function enqueue_parent_styles() {
   wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}

// wp_enqueue_script( 'jquery' );

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

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


//Making jQuery Google API
function modify_jquery() {
    if (!is_admin()) {
        // comment out the next two lines to load the local copy of jQuery
        wp_deregister_script('jquery');
		wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1');
	//	wp_register_script('jquery', 'http//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2'	);
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

/**
 * Change number of related products output
 */ 
function woo_related_products_limit() {
  global $product;
	
	$args['posts_per_page'] = 6;
	return $args;
}
add_filter( 'woocommerce_output_related_products_args', 'jk_related_products_args', 20 );
  function jk_related_products_args( $args ) {
	$args['posts_per_page'] = 4; // 4 related products
	$args['columns'] = 2; // arranged in 2 columns
	return $args;
}

function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
    case 'SUMO Reward Points' :
        $translated_text = __( 'Reward Points', 'woocommerce1' );
        break;
}
return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 20, 3 );


// heading before cart table
add_action( 'woocommerce_before_cart_table', 'heading_before_cart_table', 9, 4 );	
function heading_before_cart_table(){
	
	 echo "Weight: ".WC()->cart->get_cart_contents_weight()." KG";
	echo "<h4>Cart Product(s)</h4>";
}

// 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',
	));

}


// add_action( 'woocommerce_order_status_processing', 'order_status_processing_actions', 20, 4 ); 
function order_status_processing_actions( $order_id, $order ) {
	// bookingatmnp($order_id);
	
}


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   = '[{site_title}] Order #{order_number} 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' 	=> 'Return/Exchange Policy',
		'menu_title'	=> 'Return/Exchange Policy',
		'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 fo 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;
}

function sendonesignalpushnotification($headings,$subtitle,$content,$url,$orderid) {
	$headings    = array(
        "en" => $headings
    );
	
	$subtitle    = array(
        "en" => $subtitle
    );

	$content      = array(
        "en" => $content
    );
	
//http://localhost/vega/
	
//	$url = "http://www.itlinks.com";
	
    $hashes_array = array();
    array_push($hashes_array, array(
        "id" => "order-button",
        "text" => "Order admin",
//        "icon" => "http://i.imgur.com/N8SN8ZS.png",
        "url" => $url,
    ));
//    array_push($hashes_array, array(
//        "id" => "like-button-2",
//        "text" => "ITlinks",
//        "icon" => "http://i.imgur.com/N8SN8ZS.png",
//        "url" => "https://itlinks.com"
//    ));
    $fields = array(
        'app_id' => "99b475ee-1c74-42bf-94ec-e8655cba1c7b",
       'filters' => array(array("field" => "tag", "key" => "user_type", "relation" => "=", "value" => "admin")),
        'data' => array(
            "foo" => "bar"
        ),
        'contents' => $content,
		'headings' => $headings,
		'subtitle' => $subtitle,
		'url' => $url,
        'web_buttons' => $hashes_array
    );
    
    $fields = json_encode($fields);
   // print("\nJSON sent:\n");
    // print($fields);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic NDhjNDVhNDEtNmUwNS00ZWJkLTk2Y2ItYzNiOTNlOTBhMjYz'
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return $response;
}

/* 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 ){
	
	$order = new WC_Order( $order_id );
	
	// Start - onesignal push notification
	$subtitle ="";
	$url = site_url()."/wp-admin/post.php?post=".$order_id."&action=edit";
	$content = "Order #: ".$order_id;
	// sendonesignalpushnotification("New Order Notification",$subtitle,$content,$url,$order_id);
	// The text for the note
	$note = __("Push notification sent to administrators...");
	// Add the note
	$order->add_order_note( $note );	
	// End - onesignal push notification
   
	// Start - bookingatmnp
	$email = $order->billing_email;
	$phone = $order->billing_phone;
	$shipping_type = $order->get_shipping_method();
	$shipping_cost = $order->get_total_shipping();

	$codAmount = $order->get_total();
	$ConsigneeName = $order->get_billing_first_name().' '.$order->get_billing_last_name();
	$address = $order->get_billing_address_1().' '.$order->get_billing_address_2();
	$destinationCityName = $order->get_billing_city();
	// $DestCityId = searchForDestCityId1( $DestCityName );
	$consigneeEmail = $order->get_billing_email();
	$destinationCityName = ucfirst(strtolower($destinationCityName));
	$username = "amer_1t181";
	$password = "@thvQiiK7@QTzzK";

	$url = "http://mnpcourier.com/mycodapi/api/Booking/InsertBookingData";

	//Initiate cURL.
	$ch = curl_init($url);

	//The JSON data.
	$jsonData = array(
		'username' => $username,
		'password'	=> $password,
		'consigneeName'	=> $ConsigneeName,
		'consigneeAddress'	=> $address,
		'consigneeMobNo'	=> $phone,
		'consigneeEmail'	=> $consigneeEmail,
		'destinationCityName'	=> $destinationCityName,
		'pieces'	=> 1,
		'weight'	=> 1.0,
		'codAmount'	=> $codAmount,
		'custRefNo'	=> $order_id,
		'productDetails'	=> 'one White t shirt medium',
		'fragile'	=> 'Yes',
		'Service'	=> 'S',
		'Remarks'	=> 'Please call before delivery',
		'InsuranceValue'	=> '0'
	);

	//Encode the array into JSON.
	$jsonDataEncoded = json_encode($jsonData);

	//Tell cURL that we want to send a POST request.
	curl_setopt($ch, CURLOPT_POST, 1);

	//Attach our encoded JSON string to the POST fields.
	curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

	//Set the content type to application/json
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

	//Execute the request
	curl_exec($ch);  

	$note = __("Booking added to MNP");
	// Add the note
	$order->add_order_note( $note );
	// END  - bookingatmnp     
	
 }
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 searchForDestCityId1($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', 'my_cities' );
function my_cities( $cities ) {
    $cities['PK'] = array(
        'BA' => array( // city name with postcoe
			'CHAMAN',
			'DALBANDIN',
			'GWADAR',
			'JAFFARABAD',
			'KALAT',
			'KHUZDAR',
			'KUCHLAK',
			'LORALAI',
			'MASTUNG',
			'MUCH',
			'NAUSHKI',
			'PISHIN',
			'QUETTA',
			'TURBAT',
			'ZHOB'
		),
        'IS' => array( // just city name
			'ISLAMABAD'
		),
        'JK' => array( // just city name
			'BAGH (AJK)',
			'DADYAL (AJK)',
			'HAJEERA',
			'HATIABALA',
			'KOTLI (AJK)',
			'MANGLA (AJK)',
			'MANGLA CANTT (AJK)',
			'MIRPUR (AJK)',
			'MUZAFFARABAD (AJK)',
			'NEW INDUSTRIAL AREA ',
			'POONCH (AJK)',
			'WAPDA COLONY (AJK)'
		),
        'KP' => array( // just city name
			'ABBOTTABAD',
			'AKORA KHATTAK',
			'AMANGARH',
			'AYUBIA',
			'BAFFA',
			'BALA KOT',
			'BALAMBAT',
			'BANNU',
			'BARA MARKET',
			'BARIKOT',
			'BATGRAM',
			'BATKHELA',
			'BUNER',
			'CHAKDARA',
			'CHARBAGH',
			'CHARSADDA',
			'CHITRAL',
			'CHOTA LAHORE',
			'DAOOD ZAI',
			'DARGAI',
			'DARYA KHAN',
			'DERA ISMAIL KHAN',
			'DEWALAY',
			'DOABA',
			'DULLE WALA',
			'GHARI HABIBULLAH',
			'GHAZI',
			'HAKEEM ABAD',
			'HANGU',
			'HARIPUR',
			'HATTAR',
			'HAVELIAN',
			'HAZARA UNIVERSITY',
			'JEHANGIRA',
			'KALOR KOT',
			'KANGRA',
			'KANJU',
			'KARAK',
			'KHAS BEHAAL',
			'KHOAZA KHAILA',
			'KOHAT',
			'KULACHI',
			'LAKKI MARWAT ',
			'LOWER DIR',
			'MALAKAND',
			'MANDIAN',
			'MANKERA',
			'MANSEHRA',
			'MARDAN',
			'MATTA',
			'MINGORA',
			'NATHIA GALI',
			'NAWAN SHEHR',
			'NAWAY KALI',
			'NOOR COLONY',
			'NOWSHERA',
			'NOWSHERA KALAN',
			'NRTC (TELECOM STAFF COLLEGE)',
			'PABI',
			'PAHARPUR',
			'PAROA',
			'PESHAWAR',
			'PEZU',
			'PIRBABA',
			'PMA KAKUL',
			'PUNGIRAYIN',
			'QABAL',
			'RAJAR',
			'RAMAK',
			'RASHAKI',
			'RISALPUR',
			'SAIDU SHARIF',
			'SARAYE NORANG',
			'SARDARYAB',
			'SAWABI',
			'SAWAT',
			'SHABQADAR',
			'SHANGLA',
			'SHEEDO',
			'SHERGARH',
			'SHEWA ADDA',
			'SHIMLA HILL',
			'SIRAYE MUHAJIR',
			'SWABI',
			'TAKHT-E-BHAI',
			'TANGI',
			'TANK',
			'TARBELA DAM',
			'TIMARGARAH',
			'TOPI (GIK UNIVERSITY AREA ONLY)*',
			'UPPER DIR',
			'VILLAGE SIAL'
		),
	 'PB' => array( // just city name
			'ABDUL HAKEEM',
			'ADDA JOHAL',
			'ADDA SHAIKH WAHAN',
			'ADDA SIRAJ',
			'AHMEDPUR EAST',
			'AHMEDPUR SIAL',
			'AJNIA WALA',
			'AKHTAR ABAD',
			'ALIPUR',
			'ALIPUR CHATHA',
			'ALLAH ABAD',
			'ARIFWALA',
			'ATTOCK',
			'BADDOMALHI',
			'BAHAWALNAGAR',
			'BAHAWALPUR',
			'BAHTAR MORE',
			'BAIG PUR',
			'BASHARAT',
			'BASIRPUR',
			'BASTI MALOOK',
			'BHAGTANWALA',
			'BHAI PHERU',
			'BHAKKAR',
			'BHALWAAL',
			'BHARA KAHU',
			'BHERA',
			'BHIKKI',
			'BHIMBER (AJK)',
			'BHOWANA',
			'BHURBUN (P.C. HOTEL)',
			'BONGA HAYAT',
			'BUCHEKE',
			'BUREWALA',
			'CADET COLLEGE SUNNYBANK',
			'CHAK JHUMRA',
			'CHAK PARANA',
			'CHAKLALA',
			'CHAKRI',
			'CHAKWAL',
			'CHANGA MANGA',
			'CHAWINDA',
			'CHICHAWATNI',
			'CHINIOT',
			'CHISTIAN',
			'CHOA SAIDAN SHAH',
			'CHOWK AZAM',
			'CHOWK PANDORI ',
			'CHUNIAN',
			'DAKWALA',
			'DASKA',
			'DAUL TALA',
			'DEPALPUR',
			'DERA GHAZI KHAN',
			'DERA NAWAB',
			'DHUDIAL',
			'DIJKOT',
			'DINA ',
			'DINGA ',
			'DISTT. COMPLEX',
			'DONGA BONGA',
			'DUNIAPUR',
			'FAISALABAD',
			'FAQIRWALI',
			'FAROKA',
			'FAROOQABAD',
			'FATEH JANG',
			'FATEH PUR',
			'FATEH PUR KAMAL',
			'FAZIL PUR',
			'FEROZ WATWAN',
			'FORT ABBAS',
			'GAGGO MANDI',
			'GAMBER',
			'GARHA MORE',
			'GATWALA 199 / RB',
			'GHAKKAR MANDI',
			'GHAR MORE',
			'GHARIBWAL CEMENT',
			'GHAZIABAD',
			'GHIKA GALI ',
			'GHORA GALI',
			'GHOUR GHUSTI',
			'GOJRA',
			'GOTH MACHI',
			'GUJAR KHAN',
			'GUJRANWALA',
			'GUJRAT',
			'GULYANA',
			'HAFIZABAD',
			'HARAPPA',
			'HARNAL',
			'HAROONABAD',
			'HASEEB WAQAS MILLS',
			'HASIL PUR',
			'HASSAN ABDAL',
			'HAVELI LAKHA',
			'HAZRO',
			'HEADBALOKI ROAD',
			'HEADMARALA',
			'HUJRA SHAH MUKEEM',
			'IQBAL ABAD',
			'IQBAL NAGAR',
			'JAHANIAN',
			'JALALPUR BHATTIAN',
			'JALALPUR JATTAN',
			'JALALPURPIRWALA',
			'JAMPUR',
			'JANDIA SHER KHAN',
			'JARANWALA',
			'JATOI',
			'JHABRAN MANDI',
			'JHANG',
			'JHELUM',
			'JOHARABAD',
			'KABIRWALA',
			'KACHA KHOO',
			'KAHAUTA',
			'KALLAR KAHAR',
			'KALLAR SYEDDAN',
			'KAMALIA',
			'KAMOKE',
			'KAMRA',
			'KANGAN PUR',
			'KANYAL',
			'KAROOR PAKA',
			'KAROR LAL EASAN',
			'KASSOWAL',
			'KASUR',
			'KHAIRPUR TAMEWALI',
			'KHAN BELA',
			'KHAN GHAR',
			'KHANEWAL',
			'KHANKA DOGRAN',
			'KHANPUR',
			'KHARIAN',
			'KHUDIAN KHAS',
			'KHURRIANWALA',
			'KHUSHAB',
			'KHWERA',
			'KOT ADDU',
			'KOT CHUTTA',
			'KOT MITHAN',
			'KOT MOMIN',
			'KOT PINDI DAS',
			'KOT RADHA KISHAN',
			'KOT SAMABAH',
			'KOTLA ARAB ALI KHAN',
			'KOTLI BEHRAM',
			'KOTLI LOHARAN',
			'KUNDIAN',
			'LAHORE',
			'LALA MUSA',
			'LALIAN',
			'LALLIAN',
			'LALLIANI',
			'LAWRENCE PUR',
			'LAYYAH',
			'LIAQAT PUR',
			'LODHRAN',
			'LOWER TOPA',
			'MACHIKEY',
			'MAILSI',
			'MALAKWAL',
			'MAMU KANJAN',
			'MANA WLA',
			'MANAWALA',
			'MANDI SAFDAR ABAD',
			'MANDI USMAN WALA',
			'MANDIBAHAUDDIN',
			'MANDRA',
			'MANGA MANDI',
			'MANKYLA STATION',
			'MARI',
			'MASAR CAMP',
			'MIAN CHANNU',
			'MIAN WALI QURESHAIN',
			'MIANI',
			'MIANWALI',
			'MINCHINABAD',
			'MITHA TIWANA',
			'MORE AIMANABAD',
			'MORE KHUNDA',
			'MOTRA',
			'MULTAN',
			'MURIDKE',
			'MURREE',
			'MUZAFFARGARH',
			'NANKANA SAHIB',
			'NARANG MANDI',
			'NAROWAL',
			'NIZAMABAD',
			'NOKHAR',
			'NONAR',
			'NOOR KOT',
			'NOORPUR',
			'NOORPUR THAL',
			'NOWSHERA VIRKAN',
			'OKARA',
			'P.O.F. (FACTORY & COLONY)',
			'PAKPATTAN',
			'PASROOR',
			'PASROOR ROAD AND VILLAGES',
			'PATOKI',
			'PATRIATA',
			'PEER MAHAL',
			'PHALIA',
			'PHOOL NAGAR',
			'PIND DADAN KHAN',
			'PINDI BHATIAN',
			'PINDI GHEB',
			'PINDI GUJRAN',
			'PIPLAN',
			'PLANDARI / SADHNOTI (AJK)',
			'PUNWAN',
			'QABOOLA SHARIF',
			'QADIR PUR RAWAN',
			'QAIDABAD',
			'QAMAR MASHANI',
			'QASBA GUJRAT.',
			'QILA DEEDAR SING',
			'QILA SAIB SINGH',
			'RAHIM YAR KHAN',
			'RAIWIND',
			'RAJA JANG',
			'RAJAN PUR',
			'RAJANA',
			'RAO KHAN WALA',
			'RAWALAKOT (AJK)',
			'RAWALPINDI',
			'RAWAT',
			'RENALA KHURD',
			'RUBWA',
			'SADIQABAD',
			'SAFDARABAD',
			'SAHIWAL',
			'SAMANDARI',
			'SANGLA HILL',
			'SANJWAL',
			'SARDAR GARH',
			'SARGODHA',
			'SARI ALAMGIR',
			'SATYYANA',
			'SHADIWAL',
			'SHAHKOT',
			'SHAHPUR SADDAR',
			'SHAKARGARH',
			'SHAM KOT',
			'SHAMS ABAD',
			'SHARAQPUR SHARIF',
			'SHEIKHUPURA',
			'SHORKOT',
			'SHUJABAD',
			'SIALKOT',
			'SIHALA',
			'SIKANDARABAD',
			'SILANWALI',
			'SMAAL IND ESTATE. DASKA',
			'SOHAWA ONLY MAIN GT ROAD',
			'SUMBRIAL',
			'SUNDER ADDA',
			'SYED WALA',
			'TALAGUNG',
			'TALVANDI',
			'TANDLIAWALA',
			'TARNOL',
			'TAUNSA SHARIF',
			'TAXLA',
			'THEENG MORE (ALLAHABAD)',
			'TIBBA SULTANPURA',
			'TOBA TEK SINGH',
			'TRANDA MOHAMMAD PANAH',
			'TRANDA SAWAY KHAN',
			'TULAMBA',
			'UCH SHRIF',
			'UGGOKE',
			'VEHARI',
			'WAH CANTT',
			'WAN RAHDA RAM',
			'WARBATTAN',
			'WAZIRABAD',
			'YAZMAN',
			'ZAFARWAL',
			'ZAHIR PIR'
		),
	 'SD' => array( // just city name
			'BADIN',
			'CHOR',
			'DADU',
			'DEHARKI',
			'DERA ALLAH YAR',
			'DERA MURAD JAMALI',
			'DHABJEE',
			'DIGRI',
			'DOKRI',
			'F.F.C. PLANT',
			'GAMBAT',
			'GHARO',
			'GHOTKI',
			'GHOUS PUR',
			'GOLARCHI',
			'HALA',
			'HUB CHOWKI',
			'HUSRI',
			'HYDERABAD',
			'JACOBABAD',
			'JAMSHERO',
			'JOHI',
			'KAND KOT',
			'KANDIARO',
			'KARACHI',
			'KARAM PUR',
			'KASHMORE',
			'KHAIR PUR',
			'KHAIRPUR MEERUS',
			'KHANPUR MAHAR',
			'KHOSKI',
			'KOTRI',
			'KUNRI',
			'LARKANA',
			'MATIYARI',
			'MATLI',
			'MEHER',
			'MEHRAB PUR',
			'MIR PUR METHELO',
			'MIRPUR KHAS',
			'MITTHI',
			'MORO',
			'NASIRABAD',
			'NAWABSHAH',
			'NORIABAD',
			'NOWSHERO FEROZE',
			'NUDEARO',
			'OLD HALA',
			'PANOAQIL',
			'PITARO',
			'QAZI AHMED',
			'RADHAN',
			'RANI PUR',
			'RATO DEARO',
			'ROHRI',
			'SAEEDABAD',
			'SAJAWAL',
			'SAKRAND',
			'SANGAR',
			'SEHWAN SHARIF',
			'SHADAD KOT',
			'SHAH PUR CHAKAR',
			'SHAHDAD PUR',
			'SHAHPUR JAHANIA',
			'SHIKARPUR',
			'SIBI',
			'SUKKUR',
			'TALHAR',
			'TANDO ADAM',
			'TANDO ALLAHYAR',
			'TANDO GHULAM ALI',
			'TANDO JAM',
			'TANDO JAN MUHAMMAD',
			'TANDO MOHD KHAN',
			'THATTA',
			'THULL',
			'UBARO',
			'UMER KOT',
			'USTA MUHAMMAD'
		),
	'GB' => array( // just city name
			'GILGIT',
			'SKARDU'
		),
    );
    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(http://localhost/vega/wp-content/uploads/v-logo-280.png);
padding-bottom: 30px; 
} 
</style>
 <?php 
} add_action( 'login_enqueue_scripts', 'my_login_logo_one' );

add_filter( 'login_headerurl', 'custom_loginlogo_url' );

function custom_loginlogo_url($url) {

     return site_url();

}
?>