· 4 years ago · Mar 31, 2021, 09:56 PM
1<?php
2set_time_limit(120);
3include "json.php";
4ini_set('memory_limit', '1500M');
5
6/**
7 *
8 * The framework's functions and definitions
9 *
10 */
11
12/**
13 * ------------------------------------------------------------------------------------------------
14 * Define constants.
15 * ------------------------------------------------------------------------------------------------
16 */
17define( 'WOODMART_THEME_DIR', 		get_template_directory_uri() );
18define( 'WOODMART_THEMEROOT', 		get_template_directory() );
19define( 'WOODMART_IMAGES', 			WOODMART_THEME_DIR . '/images' );
20define( 'WOODMART_SCRIPTS', 		WOODMART_THEME_DIR . '/js' );
21define( 'WOODMART_STYLES', 			WOODMART_THEME_DIR . '/css' );
22define( 'WOODMART_FRAMEWORK', 		'/inc' );
23define( 'WOODMART_DUMMY', 			WOODMART_THEME_DIR . '/inc/dummy-content' );
24define( 'WOODMART_CLASSES', 		WOODMART_THEMEROOT . '/inc/classes' );
25define( 'WOODMART_CONFIGS', 		WOODMART_THEMEROOT . '/inc/configs' );
26define( 'WOODMART_HEADER_BUILDER',  WOODMART_THEME_DIR . '/inc/header-builder' );
27define( 'WOODMART_ASSETS', 			WOODMART_THEME_DIR . '/inc/admin/assets' );
28define( 'WOODMART_ASSETS_IMAGES', 	WOODMART_ASSETS    . '/images' );
29define( 'WOODMART_API_URL', 		'https://xtemos.com/licenses/api/' );
30define( 'WOODMART_DEMO_URL', 		'https://woodmart.xtemos.com/' );
31define( 'WOODMART_PLUGINS_URL', 	WOODMART_DEMO_URL . 'plugins/');
32define( 'WOODMART_DUMMY_URL', 		WOODMART_DEMO_URL . 'dummy-content/');
33define( 'WOODMART_SLUG', 			'woodmart' );
34define( 'WOODMART_CORE_VERSION', 	'1.0.18' );
35
36
37/**
38 * ------------------------------------------------------------------------------------------------
39 * Load all CORE Classes and files
40 * ------------------------------------------------------------------------------------------------
41 */
42
43if( ! function_exists( 'woodmart_autoload' ) ) {
44    function woodmart_autoload($className) {
45        $className = ltrim($className, '\\');
46        $fileName  = '';
47        $namespace = '';
48        if ($lastNsPos = strripos($className, '\\')) {
49            $namespace = substr($className, 0, $lastNsPos);
50            $className = substr($className, $lastNsPos + 1);
51            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
52        }
53        $className = str_replace('WOODMART_', '', $className);
54        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
55        $fileName = WOODMART_CLASSES . DIRECTORY_SEPARATOR . $fileName;
56        if( file_exists( $fileName )) {
57            require $fileName;
58        }
59    }
60
61    spl_autoload_register('woodmart_autoload');
62}
63
64$woodmart_theme = new WOODMART_Theme();
65
66/**
67 * ------------------------------------------------------------------------------------------------
68 * Enqueue styles
69 * ------------------------------------------------------------------------------------------------
70 */
71if( ! function_exists( 'woodmart_enqueue_styles' ) ) {
72	add_action( 'wp_enqueue_scripts', 'woodmart_enqueue_styles', 10000 );
73
74	function woodmart_enqueue_styles() {
75		$version = woodmart_get_theme_info( 'Version' );
76		$minified = woodmart_get_opt( 'minified_css' ) ? '.min' : '';
77		$is_rtl = is_rtl() ? '-rtl' : '';
78		$style_url = WOODMART_THEME_DIR . '/style' . $minified . '.css';
79		if ( woodmart_woocommerce_installed() && is_rtl() ) {
80			$style_url = WOODMART_STYLES . '/style-rtl' . $minified . '.css';
81		} elseif ( ! woodmart_woocommerce_installed() ) {
82			$style_url = WOODMART_STYLES . '/base' . $is_rtl . $minified . '.css';
83		}
84
85		// Custom CSS generated from the dashboard
86
87		$file = get_option('woodmart-generated-css-file');
88		if( ! empty( $file ) && ! empty( $file['url'] ) ) {
89			$style_url = $file['url'];
90		}
91
92		wp_deregister_style( 'dokan-fontawesome' );
93		wp_dequeue_style( 'dokan-fontawesome' );
94
95		wp_deregister_style( 'font-awesome' );
96		wp_dequeue_style( 'font-awesome' );
97
98		wp_dequeue_style( 'vc_pageable_owl-carousel-css' );
99		wp_dequeue_style( 'vc_pageable_owl-carousel-css-theme' );
100		
101		if ( ! woodmart_get_opt( 'disable_font_awesome_theme_css' ) ) {
102			wp_enqueue_style('font-awesome-css', WOODMART_STYLES . '/font-awesome.min.css', array(), $version);
103		}
104	
105		wp_enqueue_style( 'bootstrap', WOODMART_STYLES . '/bootstrap.min.css', array(), $version );
106		wp_enqueue_style( 'woodmart-style', $style_url, array( 'bootstrap' ), $version );
107
108		wp_enqueue_style( 'js_composer_front', false, array(), $version );
109		
110		// load typekit fonts
111		$typekit_id = woodmart_get_opt( 'typekit_id' );
112
113		if ( $typekit_id ) {
114			wp_enqueue_style( 'woodmart-typekit', 'https://use.typekit.net/' . esc_attr ( $typekit_id ) . '.css', array(), $version );
115		}
116
117		remove_action('wp_head', 'print_emoji_detection_script', 7);
118		remove_action('wp_print_styles', 'print_emoji_styles');
119
120		wp_register_style( 'woodmart-inline-css', false );
121	}
122}
123
124/**
125 * ------------------------------------------------------------------------------------------------
126 * Enqueue scripts
127 * ------------------------------------------------------------------------------------------------
128 */
129 
130if( ! function_exists( 'woodmart_enqueue_scripts' ) ) {
131	add_action( 'wp_enqueue_scripts', 'woodmart_enqueue_scripts', 10000 );
132
133	function woodmart_enqueue_scripts() {
134		
135		$version = woodmart_get_theme_info( 'Version' );
136		/*
137		 * Adds JavaScript to pages with the comment form to support
138		 * sites with threaded comments (when in use).
139		 */
140		if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
141			wp_enqueue_script( 'comment-reply', false, array(), $version );
142		}
143		if( ! woodmart_woocommerce_installed() ) {
144			wp_register_script( 'js-cookie', woodmart_get_script_url( 'js.cookie' ), array( 'jquery' ), $version, true );
145		}
146
147		wp_dequeue_script( 'flexslider' );
148		wp_dequeue_script( 'photoswipe-ui-default' );
149		wp_dequeue_script( 'prettyPhoto-init' );
150		wp_dequeue_script( 'prettyPhoto' );
151		wp_dequeue_style( 'photoswipe-default-skin' );
152		if( woodmart_get_opt( 'image_action' ) != 'zoom' ) {
153			wp_dequeue_script( 'zoom' );
154		}
155
156		wp_enqueue_script( 'wpb_composer_front_js', false, array(), $version );
157		wp_enqueue_script( 'imagesloaded', false, array(), $version );
158
159		if( woodmart_get_opt( 'combined_js' ) ) {
160		    wp_enqueue_script( 'isotope', woodmart_get_script_url( 'isotope.pkgd' ), array(), $version, true );
161		    wp_enqueue_script( 'woodmart-theme', WOODMART_SCRIPTS . '/theme.min.js', array( 'jquery', 'js-cookie' ), $version, true );
162		} else {
163			wp_enqueue_script( 'woodmart-owl-carousel', woodmart_get_script_url( 'owl.carousel' ), array(), $version, true );
164			wp_enqueue_script( 'woodmart-tooltips', woodmart_get_script_url( 'jquery.tooltips' ), array(), $version, true );
165			wp_enqueue_script( 'woodmart-magnific-popup', woodmart_get_script_url( 'jquery.magnific-popup' ), array(), $version, true );
166			wp_enqueue_script( 'woodmart-device', woodmart_get_script_url( 'device' ), array( 'jquery' ), $version, true );
167			wp_enqueue_script( 'woodmart-waypoints', woodmart_get_script_url( 'waypoints' ), array( 'jquery' ), $version, true );
168
169			if ( woodmart_get_opt( 'disable_nanoscroller' ) != 'disable' ) {
170				wp_enqueue_script( 'woodmart-nanoscroller', woodmart_get_script_url( 'jquery.nanoscroller' ), array(), $version, true );
171			}
172
173			$minified = woodmart_get_opt( 'minified_js' ) ? '.min' : '';
174			$base = ! woodmart_woocommerce_installed() ? '-base' : '';
175			wp_enqueue_script( 'woodmart-theme', WOODMART_SCRIPTS . '/functions' . $base . $minified . '.js', array( 'js-cookie' ), $version, true );
176			if ( woodmart_get_opt( 'ajax_shop' ) && woodmart_woocommerce_installed() && ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) ) {
177				wp_enqueue_script( 'woodmart-pjax', woodmart_get_script_url( 'jquery.pjax' ), array(), $version, true );
178			}
179		}
180 		wp_add_inline_script( 'woodmart-theme', woodmart_settings_js(), 'after' );
181		
182		wp_register_script( 'woodmart-panr-parallax', woodmart_get_script_url( 'panr-parallax' ), array(), $version, true );
183		wp_register_script( 'woodmart-photoswipe', woodmart_get_script_url( 'photoswipe-bundle' ), array(), $version, true );
184		wp_register_script( 'woodmart-slick', woodmart_get_script_url( 'slick' ), array(), $version, true );
185		wp_register_script( 'woodmart-countdown', woodmart_get_script_url( 'countdown' ), array(), $version, true );
186		wp_register_script( 'woodmart-packery-mode', woodmart_get_script_url( 'packery-mode.pkgd' ), array(), $version, true );
187		wp_register_script( 'woodmart-vivus', woodmart_get_script_url( 'vivus' ), array(), $version, true );
188		wp_register_script( 'woodmart-threesixty', woodmart_get_script_url( 'threesixty' ), array(), $version, true );
189		wp_register_script( 'woodmart-justifiedGallery', woodmart_get_script_url( 'jquery.justifiedGallery' ), array(), $version, true );
190		wp_register_script( 'woodmart-autocomplete', woodmart_get_script_url( 'jquery.autocomplete' ), array(), $version, true );
191		wp_register_script( 'woodmart-sticky-kit', woodmart_get_script_url( 'jquery.sticky-kit' ), array(), $version, true );
192		wp_register_script( 'woodmart-parallax', woodmart_get_script_url( 'jquery.parallax' ), array(), $version, true );
193		wp_register_script( 'woodmart-parallax-scroll', woodmart_get_script_url( 'parallax-scroll' ), array(), $version, true );
194		wp_register_script( 'maplace', woodmart_get_script_url( 'maplace-0.1.3' ), array( 'google.map.api' ), $version, true );
195		wp_register_script( 'isotope', woodmart_get_script_url( 'isotope.pkgd' ), array(), $version, true );
196
197		if ( woodmart_woocommerce_installed() ) {
198			wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting.min.js', array( 'jquery' ), $version, true );
199			wp_register_script( 'wc-jquery-ui-touchpunch', WC()->plugin_url() . '/assets/js/jquery-ui-touch-punch/jquery-ui-touch-punch.min.js', array( 'jquery-ui-slider' ), $version, true );
200		}
201	
202		// Add virations form scripts through the site to make it work on quick view
203		if( woodmart_get_opt( 'quick_view_variable' ) || woodmart_get_opt( 'quick_shop_variable' ) ) {
204			wp_enqueue_script( 'wc-add-to-cart-variation', false, array(), $version );
205		}
206
207		$translations = array(
208			'adding_to_cart' => esc_html__('Processing', 'woodmart'),
209			'added_to_cart' => esc_html__('Product was successfully added to your cart.', 'woodmart'),
210			'continue_shopping' => esc_html__('Continue shopping', 'woodmart'),
211			'view_cart' => esc_html__('View Cart', 'woodmart'),
212			'go_to_checkout' => esc_html__('Checkout', 'woodmart'),
213			'loading' => esc_html__('Loading...', 'woodmart'),
214			'countdown_days' => esc_html__('days', 'woodmart'),
215			'countdown_hours' => esc_html__('hr', 'woodmart'),
216			'countdown_mins' => esc_html__('min', 'woodmart'),
217			'countdown_sec' => esc_html__('sc', 'woodmart'),
218			'cart_url' => ( woodmart_woocommerce_installed() ) ?  esc_url( wc_get_cart_url() ) : '',
219			'ajaxurl' => admin_url('admin-ajax.php'),
220			'add_to_cart_action' => ( woodmart_get_opt( 'add_to_cart_action' ) ) ? esc_js( woodmart_get_opt( 'add_to_cart_action' ) ) : 'widget',
221			'added_popup' => ( woodmart_get_opt( 'added_to_cart_popup' ) ) ? 'yes' : 'no',
222			'categories_toggle' => ( woodmart_get_opt( 'categories_toggle' ) ) ? 'yes' : 'no',
223			'enable_popup' => ( woodmart_get_opt( 'promo_popup' ) ) ? 'yes' : 'no',
224			'popup_delay' => ( woodmart_get_opt( 'promo_timeout' ) ) ? (int) woodmart_get_opt( 'promo_timeout' ) : 1000,
225			'popup_event' => woodmart_get_opt( 'popup_event' ),
226			'popup_scroll' => ( woodmart_get_opt( 'popup_scroll' ) ) ? (int) woodmart_get_opt( 'popup_scroll' ) : 1000,
227			'popup_pages' => ( woodmart_get_opt( 'popup_pages' ) ) ? (int) woodmart_get_opt( 'popup_pages' ) : 0,
228			'promo_popup_hide_mobile' => ( woodmart_get_opt( 'promo_popup_hide_mobile' ) ) ? 'yes' : 'no',
229			'product_images_captions' => ( woodmart_get_opt( 'product_images_captions' ) ) ? 'yes' : 'no',
230			'ajax_add_to_cart' => ( apply_filters( 'woodmart_ajax_add_to_cart', true ) ) ? woodmart_get_opt( 'single_ajax_add_to_cart' ) : false,
231			'all_results' => esc_html__('View all results', 'woodmart'),
232			'product_gallery' => woodmart_get_product_gallery_settings(),
233			'zoom_enable' => ( woodmart_get_opt( 'image_action' ) == 'zoom') ? 'yes' : 'no',
234			'ajax_scroll' => ( woodmart_get_opt( 'ajax_scroll' ) ) ? 'yes' : 'no',
235			'ajax_scroll_class' => apply_filters( 'woodmart_ajax_scroll_class' , '.main-page-wrapper' ),
236			'ajax_scroll_offset' => apply_filters( 'woodmart_ajax_scroll_offset' , 100 ),
237			'infinit_scroll_offset' => apply_filters( 'woodmart_infinit_scroll_offset' , 300 ),
238			'product_slider_auto_height' => ( woodmart_get_opt( 'product_slider_auto_height' ) ) ? 'yes' : 'no',
239			'price_filter_action' => ( apply_filters( 'price_filter_action' , 'click' ) == 'submit' ) ? 'submit' : 'click',
240			'product_slider_autoplay' => apply_filters( 'woodmart_product_slider_autoplay' , false ),
241			'close' => esc_html__( 'Close (Esc)', 'woodmart' ),
242			'share_fb' => esc_html__( 'Share on Facebook', 'woodmart' ),
243			'pin_it' => esc_html__( 'Pin it', 'woodmart' ),
244			'tweet' => esc_html__( 'Tweet', 'woodmart' ),
245			'download_image' => esc_html__( 'Download image', 'woodmart' ),
246			'cookies_version' => ( woodmart_get_opt( 'cookies_version' ) ) ? (int)woodmart_get_opt( 'cookies_version' ) : 1,
247			'header_banner_version' => ( woodmart_get_opt( 'header_banner_version' ) ) ? (int)woodmart_get_opt( 'header_banner_version' ) : 1,
248			'promo_version' => ( woodmart_get_opt( 'promo_version' ) ) ? (int)woodmart_get_opt( 'promo_version' ) : 1,
249			'header_banner_close_btn' => woodmart_get_opt( 'header_close_btn' ),
250			'header_banner_enabled' => woodmart_get_opt( 'header_banner' ),
251			'whb_header_clone' => woodmart_get_config( 'header-clone-structure' ),
252			'pjax_timeout' => apply_filters( 'woodmart_pjax_timeout' , 5000 ),
253			'split_nav_fix' => apply_filters( 'woodmart_split_nav_fix' , false ),
254			'shop_filters_close' => woodmart_get_opt( 'shop_filters_close' ) ? 'yes' : 'no',
255			'woo_installed' => woodmart_woocommerce_installed(),
256			'base_hover_mobile_click' => woodmart_get_opt( 'base_hover_mobile_click' ) ? 'yes' : 'no',
257			'centered_gallery_start' => apply_filters( 'woodmart_centered_gallery_start' , 1 ),
258			'quickview_in_popup_fix' => apply_filters( 'woodmart_quickview_in_popup_fix', false ),
259			'disable_nanoscroller' => woodmart_get_opt( 'disable_nanoscroller' ),
260			'one_page_menu_offset' => apply_filters( 'woodmart_one_page_menu_offset', 150 ),
261			'hover_width_small' => apply_filters( 'woodmart_hover_width_small', true ),
262			'is_multisite' => is_multisite(),
263			'current_blog_id' => get_current_blog_id(),
264			'swatches_scroll_top_desktop' => woodmart_get_opt( 'swatches_scroll_top_desktop' ),
265			'swatches_scroll_top_mobile' => woodmart_get_opt( 'swatches_scroll_top_mobile' ),
266			'lazy_loading_offset' => woodmart_get_opt( 'lazy_loading_offset' ),
267			'add_to_cart_action_timeout' => woodmart_get_opt( 'add_to_cart_action_timeout' ) ? 'yes' : 'no',
268			'add_to_cart_action_timeout_number' => woodmart_get_opt( 'add_to_cart_action_timeout_number' ),
269			'single_product_variations_price' => woodmart_get_opt( 'single_product_variations_price' ) ? 'yes' : 'no',
270			'google_map_style_text' => esc_html__( 'Custom style', 'woodmart' ),
271		);
272		
273		wp_localize_script( 'woodmart-functions', 'woodmart_settings', $translations );
274		wp_localize_script( 'woodmart-theme', 'woodmart_settings', $translations );
275
276	}
277}
278
279/**
280 * ------------------------------------------------------------------------------------------------
281 * Get script URL
282 * ------------------------------------------------------------------------------------------------
283 */
284if( ! function_exists( 'woodmart_get_script_url') ) {
285	function woodmart_get_script_url( $script_name ) {
286	    return WOODMART_SCRIPTS . '/' . $script_name . '.min.js';
287	}
288}
289
290
291/**
292 * ------------------------------------------------------------------------------------------------
293 * Enqueue style for inline css
294 * ------------------------------------------------------------------------------------------------
295 */
296
297if ( ! function_exists( 'woodmart_enqueue_inline_style_anchor' ) ) {
298	function woodmart_enqueue_inline_style_anchor() {
299		wp_enqueue_style( 'woodmart-inline-css' );
300	}
301	
302	add_action( 'wp_footer', 'woodmart_enqueue_inline_style_anchor', 10 );
303}
304
305
306add_filter( 'woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4 );
307function my_woocommerce_rest_check_permissions( $permission, $context, $object_id, $post_type  ){
308  return true;
309}
310
311
312function get_wc_product_by_title( $title, $post_marca){
313    global $wpdb;
314	global $postTitle; 
315
316    $post_title =  urldecode(strval($title));
317	$post_marca =  urldecode(strval($post_marca));
318	$postTitle[] = $post_title; 
319	
320	$title_name_marca = $post_title . ", ". $post_marca; 
321
322	//echo "IMPRIMINDO OS TÍTULOS PASSADOS PELO WS";
323	//var_dump($postTitle);
324	
325    $post_table = $wpdb->prefix . "posts";
326    $result = $wpdb->get_col(
327		"SELECT 
328			posts.ID, posts.post_title
329			FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
330			ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
331			ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id 
332			INNER JOIN wp_terms AS terms 
333			ON term_taxonomy.term_id = terms.term_id 
334			WHERE term_taxonomy.taxonomy = 'product_type' 
335			AND posts.post_title LIKE '%$title_name_marca%'
336			AND posts.post_type = 'product'"
337	);
338	
339	//var_dump($post_title);
340	//var_dump($result);
341	// We exit if title doesn't match
342	$result2 = $wpdb->get_col(
343		"SELECT 
344			posts.ID, posts.post_title
345			FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
346			ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
347			ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id 
348			INNER JOIN wp_terms AS terms 
349			ON term_taxonomy.term_id = terms.term_id 
350			WHERE term_taxonomy.taxonomy = 'product_type'
351			AND  posts.post_status NOT IN('trash')
352			AND posts.post_title LIKE '%$title_name_marca%'
353			AND posts.post_type = 'product'"
354	);
355
356	if(empty($result2[0])){
357		return;
358	}
359	else{
360
361		//var_dump($result2[0]);
362	}
363
364    if( empty( $result[0] ) ) 
365        return;
366	else
367		//print_r(wc_get_product( intval( $result[0])));
368        return wc_get_product( $result2[0] );
369}
370
371function getProdutosForWikiWs(){
372	/*
373	$ch = curl_init();
374	curl_setopt_array($ch, array(
375	//CURLOPT_URL => "http://app.wikisistemas.com.br:8086/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=392&guid=4c6e6dab-6d6d-43d9-8f71-7f12158f8f85&estoquePositivo=0",
376	CURLOPT_URL => "http://52.6.107.225/script.php?wikiProducts=true",
377	CURLOPT_RETURNTRANSFER => true,
378	CURLOPT_ENCODING => "",
379	CURLOPT_MAXREDIRS => 10,
380	CURLOPT_TIMEOUT => 30,
381	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
382	CURLOPT_CUSTOMREQUEST => "GET",
383	CURLOPT_SSL_VERIFYPEER=> false,
384  
385	CURLOPT_HTTPHEADER => array(
386		"Authorization: Basic *****************",
387		"Cache-Control: no-cache"
388	),  
389	));
390  
391	$result = curl_exec($ch);
392	*/
393	$collection = json_decode(_getJson());
394	//$collection = json_decode($result);
395	return $collection;	
396	
397	//curl_close($ch);
398  }
399
400/*
401//usage
402$parent_id = 746; // Or get the variable product id dynamically
403
404//The variation data
405$variation_data =  array(
406    'attributes' => array(
407        'size'  => 'M',
408        'color' => 'Green',
409    ),
410    'sku'           => '',
411    'regular_price' => '22.00',
412    'sale_price'    => '',
413    'stock_qty'     => 10,
414);
415
416// The function to be run
417create_product_variation( $parent_id, $variation_data );
418*/
419
420function insertSimpleProduct(){
421	$post = array(
422		'post_author' => $user_id,
423		'post_content' => '',
424		'post_status' => "publish",
425		'post_title' => $product->part_num,
426		'post_parent' => '',
427		'post_type' => "product",
428	);
429	
430	//Create post
431	$post_id = wp_insert_post( $post, $wp_error );
432	if($post_id){
433		$attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
434		add_post_meta($post_id, '_thumbnail_id', $attach_id);
435	}
436	
437	wp_set_object_terms( $post_id, 'Races', 'product_cat' );
438	wp_set_object_terms( $post_id, 'simple', 'product_type');
439	
440	update_post_meta( $post_id, '_visibility', 'visible' );
441	update_post_meta( $post_id, '_stock_status', 'instock');
442	update_post_meta( $post_id, 'total_sales', '0');
443	update_post_meta( $post_id, '_downloadable', 'yes');
444	update_post_meta( $post_id, '_virtual', 'yes');
445	update_post_meta( $post_id, '_regular_price', "1" );
446	update_post_meta( $post_id, '_sale_price', "1" );
447	update_post_meta( $post_id, '_purchase_note', "" );
448	update_post_meta( $post_id, '_featured', "no" );
449	update_post_meta( $post_id, '_weight', "" );
450	update_post_meta( $post_id, '_length', "" );
451	update_post_meta( $post_id, '_width', "" );
452	update_post_meta( $post_id, '_height', "" );
453	update_post_meta( $post_id, '_sku', "");
454	update_post_meta( $post_id, '_product_attributes', array());
455	update_post_meta( $post_id, '_sale_price_dates_from', "" );
456	update_post_meta( $post_id, '_sale_price_dates_to', "" );
457	update_post_meta( $post_id, '_price', "1" );
458	update_post_meta( $post_id, '_sold_individually', "" );
459	update_post_meta( $post_id, '_manage_stock', "no" );
460	update_post_meta( $post_id, '_backorders', "no" );
461	update_post_meta( $post_id, '_stock', "" );
462}
463
464//add_action( 'woocommerce_thankyou', 'initMigration', 20, 2 );
465
466function initMigration(){
467	/*
468	for($i=0;$i<=186;$i++){
469		//FavelaMigration::init($prodPosition=185);
470		echo "no loop: {$i}";
471		FavelaMigration::init($i);
472	}
473	return;*/
474	//pega todos os dados do WS
475	$collection = getProdutosForWikiWs();
476	//cria um array de nomes remotos
477    
478	$totalRemoteP = count($collection);
479	
480	for($i=0;$i <= count($collection);$i++){
481		//FavelaMigration::init($prodPosition=185);
482		echo "no loop: {$i} [{$totalRemoteP}]";
483		FavelaMigration::init($i);
484	}
485	
486
487	$remoteName = [];
488	foreach($collection as $cln=>$coll){
489		$remoteName[] = "{$coll->produtoNome}, {$coll->produtoMarca}";
490	}
491
492	#inicializa variáveis de operacao 
493	//variaveis locais
494	$localProducts = FavelaMigration::getAllLocalProducts();
495	//var_dump($localProducts);
496	$notExistsProduct = [];
497	//total de ids (local/remoto)
498	$totalIds = [];
499	$idsQDiferetem = [];
500	$idsQBatem = [];
501	$totalNames = [];
502	$remoteSlug = new stdClass;
503	$remoteProductSku = new stdClass;
504	$localSlugs = new stdClass;
505	$localProductName = new stdClass;
506	$rmNames = [];
507	$lcNames = [];
508	$localProductName->name = [];
509	$countIdsQDiferem = 0;
510
511	foreach($localProducts as $k=>$lp){
512		foreach($collection as $c=>$cl){
513			$resultSearch = FavelaMigration::searchProduct($cl);
514			
515			if(empty($resultSearch)){
516				$notExistsProduct[] = $resultSearch;			
517			}else{
518				//Se existe na base local um produto correspondente ao remoto.
519				$produtoName[$c] = "{$cl->produtoNome}, {$cl->produtoMarca}";
520				$productSlug[$c] = $resultSearch->get_slug();
521				$totalIds[] = $resultSearch->get_id();	
522				$remoteSlug->slug[] =  $resultSearch->get_slug();
523				$localSlugs->slug[] = $lp->get_slug();
524				$remoteProductSku->sku[] =  $resultSearch->get_sku();
525				$localProductName->name[] = "{$lp->get_name()}, {$cl->produtoMarca}";
526			}				
527			// && $remoteProductSku->sku[$c] == $lp->get_sku()
528			if($lp->get_slug() == $remoteSlug->slug[$c]){
529				echo "*Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
530					c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
531					slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]} status:[Bate com o WS
532					id:{$totalIds[$c]}] <br>";
533				  
534				  
535				echo "(ids iguais)k: {$c} |  : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";			
536				$idsQBatem[] = $lp->get_id();
537				$slugsQBatem[] =  $lp->get_slug();
538				//$totalNames[] = $resultSearch->get_name();
539				$rmNames[] = ['name'=>$remoteName[$c], 'slug'=>$remoteSlug->slug[$c],'id'=>$totalIds[$c], 'sku'=>$remoteProductSku->sku];
540				$lcNames[] = ['name'=>$lp->get_name(), 'slug'=>$lp->get_slug(),'id'=>$lp->get_id(), 'sku'=>$lp->get_sku()];
541				
542			}
543			else{
544				echo "-Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()}, 
545				c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
546				slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]}
547				status:[Não Bate com o WS id:{$totalIds[$c]}] <br>";
548
549				echo "(ids Diferem)k: {$c} |  : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
550				$idsQDiferetem[] = $lp->get_id();
551				$slugsQDiferem[] =  $lp->get_slug();		
552			}
553		}
554	}
555
556	
557	echo "<br><b>ids Que Batem</b><br>";
558	var_dump(count($idsQBatem));
559	print_r($idsQBatem);
560
561	echo "<b>Total Ids do WebService</b><br>";
562	//var_dump(count($totalIds));
563	echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
564	var_dump(count($notExistsProduct));
565	
566	echo "<b>Ids que diferem</b><br>";
567	$result = array_unique($idsQDiferetem);
568	//print_r($result);
569	var_dump(count($result));
570	print_r($result);
571
572	echo "<b>Diff dos 2 arrays(ids)</b><br>";
573	//Ids que diferem | ids que batem
574	$diffResult = array_diff($result, $idsQBatem);
575
576	var_dump(count($diffResult));
577	//var_dump($diffResult);
578	
579	echo "<b>Produtos do Diff</b><br>";
580	print_r($diffResult);
581	$deletedIds = $diffResult;
582	
583	/***/
584
585	echo "<br><b>Slugs Que Batem</b><br>";
586	var_dump(count($slugsQBatem));
587	print_r($slugsQBatem);
588
589	echo "<b>Total Ids do WebService</b><br>";
590	//var_dump(count($totalIds));
591	echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
592	var_dump(count($notExistsProduct));
593	
594	echo "<b>Slugs que diferem</b><br>";
595	$resultSlug = array_unique($slugsQDiferem);
596	//print_r($result);
597	var_dump(count($resultSlug));
598	print_r($resultSlug);
599
600	echo "<b>Diff dos 2 arrays(slugs)</b><br>";
601	//Ids que diferem | ids que batem
602	$diffResultSlug = array_diff($resultSlug, $slugsQBatem);
603
604	var_dump(count($diffResultSlug));
605	//var_dump($diffResult);
606	
607	echo "<b>Produtos do Diff</b><br>";
608	print_r($diffResultSlug);
609	//$deletedIds = $diffResult;
610
611/*
612	echo "<b>Diff das Slugs</b><br>";
613	$diffResultSlugs = array_diff($localSlugs->slug, $remoteSlug->slug);
614	$resultSlug = array_unique($diffResultSlugs);
615	
616	var_dump(count($diffResultSlugs));
617	//print_r($diffResultSlugs);
618	echo "<b>Slug processado excluido os Repetidos</b><br>";
619	var_dump(count($resultSlug));
620	//var_dump($resultSlug);
621	//var_dump($diffResultSlugs);
622	
623	
624	echo " <b>Diff dos Nomes(locais/remotos)</b><br>";
625	$diffResultNames = array_diff($totalNames, $remoteName);
626	var_dump(count($diffResultNames));
627	//print_r($diffResultNames);
628	echo "<b>Total de nomes que Batem</b><br>";
629	var_dump(count($totalNames));
630
631	echo "<b>Total de nomes do Ws</b><br>";
632	var_dump(count($remoteName));
633
634	echo "<b>Remote Info Produtcs{names}</b><br>";
635	var_dump(count($rmNames));
636	//print_r($rmNames);
637
638	echo "<b>Local Info Produtcs{names}</b><br>";
639	var_dump(count($lcNames));
640	//print_r($lcNames);
641	//print_r($diffResultNames);
642*/
643   if(isset($deletedIds)){
644			$productNameDelIds = [];
645			foreach($deletedIds as $d => $pDelete){
646				$product = wc_get_product($pDelete);
647				$productNameDelIds[] = ['name'=>$product->get_name(), 'id'=>$product->get_id(), 'sku'=>$product->get_sku()];
648				//echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDelete} | nome: {$productNameDelIds[$x]}]<br>";
649				//wh_deleteProduct($pDelete);
650				//$product = wc_get_product($pDelete);
651				//$product->delete();
652				//$result = 'trash' === $product->get_status();
653	/*
654				if (!$result)
655				   {
656					//return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
657				}
658				$x++;*/
659			}
660		}
661	
662	//var_dump($productNameDelIds);
663
664	//$u = 0;
665	foreach($collection as $ck=>$coll){
666		//stristr($string, 'earth') === FALSE
667		foreach($productNameDelIds as $pk=>$pDeIds){
668			//var_dump($pDeIds);
669			if(is_string($pDeIds['name'])){
670				$pname = explode(",", $pDeIds['name']);
671				if(preg_match("/{$pname[0]}/i", $coll->produtoNome)){
672					echo "Existe na base [{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:{$ck} | <br>";
673					//unset($pname[0]);
674					unset($productNameDelIds[$pk]);
675			
676				}else{
677					if((count($collection)-1) == $ck){
678						echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDeIds['id']} | nome: {$pname[0]}] collection-k:{$ck} <br>";
679						//wh_deleteProduct($pDelete);
680						$product = wc_get_product($pDeIds['id']);
681						$product->delete();
682						echo "Não Existe na base [{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:{$ck} |<br>";
683					}
684				}
685
686			}
687			
688		}
689
690	}
691    
692
693
694
695
696
697	//61
698	//FavelaMigration::init($prodPosition=61);
699	//186
700	/*
701	$bate = 0;
702	foreach($collection as $k=> $coll){
703
704		//FavelaMigration::init($prodPosition=185);
705		//echo "no loop: {$i}";
706		//$productsOp[] = FavelaMigration::init($i);
707
708		$productTeste = $coll;
709		$resultSearch = FavelaMigration::searchProduct($productTeste);
710		if(empty($resultSearch)){
711			echo "<h4>Produto não existe na base Local</h4>";
712				
713		}else{
714			$totalIds[] = $resultSearch->get_id();
715			//echo "<h4>Produto existe na base Local</h2>";
716				//var_dump($resultSearch); 
717		}
718		
719		$produtoName = "{$coll->produtoNome}, {$coll->produtoMarca}";
720		
721		foreach($totalIds as $t=>$tIds){
722			if($localProducts[$t]->get_id() == $tIds){
723				echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$k]->get_id()} ({$k}) Produto(Remoto)Nome:$produtoName [Bate com o WS (id:{$tIds})] Bate: [{$bate}]<br>";				 
724				$bate++;
725				//echo "(ids iguais) k: {$k} | t: [{$t}] : ids remoto: " . ($tIds) . " ids local: {$localProducts[$t]->get_id()} <br>";		
726				echo "(ids iguais)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
727				//unset($lp);
728				//$listVerify['produtoBate'] = $localProducts[$prodPosition];
729				//$listNoExists = $lp; 
730			}else{
731	
732				//echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$i]->get_id()}[c:{$i}] ({$i}) Produto(Remoto)Nome:$produtoName [Não Bate com o WS (id:{$totalIds[0]})]<br>";
733				
734				//unset($localProducts);
735				echo "(ids diferentes)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
736			}
737		}
738		
739		//echo "<h4>Total de produtos Locais</h4>";
740		
741
742	}*/
743
744	//print_r($listVerify);
745	//print_r($totalIds);
746
747
748	//return $listVerify;
749
750
751
752	//echo "<h4>Produtos Operacionais</h4>";
753	//print_r($productsOp);
754	//var_dump($productsOp["produtoBate"]);
755}
756
757class MigrationRules {
758	
759	private static $lproduct, $rproduct, $collection,
760		$postId, $prodPosition, $productTeste, $remoteAttr;
761	
762	private static $tamanhoUpdated = false;
763	private static $isUpdated = false;
764
765	static function filterVariations($post_id,$meta_key,$meta_value) {
766			$query = new \WP_Query( array(
767				'post_parent' => $post_id,
768				'post_status' => 'publish',
769				'post_type' => 'product_variation',
770				'posts_per_page' => -1,
771				'meta_query' => array( array(
772					'key' => $meta_key,
773					'value' => $meta_value,
774				) ),
775			) );
776			$result = array();
777			if($query->have_posts()){
778				while ($query->have_posts()) {
779					$query->next_post();
780					$result[] = $query->post;
781				}
782				wp_reset_postdata();
783			}
784		wp_reset_query();
785		
786		return $result;
787	}
788/*
789*
790
791**/
792		static function _filterVariations($post_id,array $properties) {
793			$query = new \WP_Query( array(
794				'post_parent' => $post_id,
795				'post_status' => 'publish',
796				'post_type' => 'product_variation',
797				'posts_per_page' => -1,
798				'meta_query' => array(
799					'relation' => 'AND',
800					'cor_clause' => array(
801						'key' => $properties['cor_key'],
802						'value' => $properties['cor_value'],
803					),
804					'tamanho_clause' => array(
805						'key' => $properties['tamanho_key'],
806						'value' => $properties['tamanho_value'],
807					), 
808				),
809			) );
810			$result = array();
811			if($query->have_posts()){
812				while ($query->have_posts()) {
813					$query->next_post();
814					$result[] = $query->post;
815				}
816				wp_reset_postdata();
817			}
818		wp_reset_query();
819		
820		return $result;
821	}
822
823	static function storeStock($listCorT, $x){
824		$rtotal = self::getTotalRemoteProducts();				//trata os dados do estoque
825		
826		if(strlen($listCorT->produtoQtdeEstoque) <= 4){
827			$_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
828		} else{
829			$_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
830		}
831		echo "Attr com problema<br>";
832		var_dump($listCorT->produtoCor);
833
834		echo "{Cor:[{$listCorT->produtoCor}], Tamanho:[{$listCorT->produtoTamanho}] Será persistido} | (x:{$x},total:{$rtotal}) | <br>";
835			$variation_data = [
836				'attributes'  => [
837					'cor'     => $listCorT->produtoCor,
838					'tamanho' => $listCorT->produtoTamanho,
839					],
840				'sku'            => MigrationRules::getProductTeste()->produtoId,
841				'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
842				'sale_price'     => MigrationRules::getProductTeste()->produtoPrecoPromo,
843				'stock_qty'      => $_stockRemote
844				];
845							// The function to be run
846				_create_product_variation(MigrationRules::getPostId(), $variation_data );
847	}
848
849	static function updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts){
850		$rtotal = self::getTotalRemoteProducts();				//trata os dados do estoque
851		$totalL = self::getTotalLocalProducts();
852		$diffProducts  = $rtotal-$totalL;
853
854		if(strlen($listCorT->produtoQtdeEstoque) <= 4){
855			$_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
856		} else{
857			$_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
858		}
859
860		$pcor = strtolower(tirarAcentos($listCorT->produtoCor));
861		$acor = strtolower(tirarAcentos($attrCor));
862
863		$corFragment = explode(" ", $pcor);
864		
865		if(isset($corFragment[0])){
866			$pcor = $corFragment[0]; 
867		}
868
869		if(isset($corFragment[1])){
870			$pcor = $corFragment[0] . "-" . $corFragment[1];
871		}
872		
873
874		$rTamanho = strtolower(tirarAcentos($listCorT->produtoTamanho));
875		$atTamanho = strtolower(tirarAcentos($attrTamanho));
876
877		if($pcor == $acor){
878			//atualiza
879			echo "produtoCor:[{$pcor}] são iguais AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
880					//se o tamanho do produto for igual
881			if($rTamanho == $attrTamanho){
882				//atualiza
883				echo "produtoTamanho:[{$rTamanho}] são iguais attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
884
885				//se o estoque remoto for igual ao estoque local (Não atualiza) 
886				if($_stockRemote == $attrStock){
887					//não atualiza
888					echo "produtoQtdeEstoque:[{$_stockRemote}] são iguais{NÃO ATUALIZA} attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
889					echo "<hr><hr>";
890					//self::$isUpdated = true;
891				}
892				
893				//se estoque remoto for maior que o estoque local (Atualiza)
894				if($_stockRemote > $attrStock){
895					//atualiza
896					//var_dump(self::$isUpdated);
897				
898						echo "condition:(<i>produto tem cor e tamanho iguais e estoque local menor do que o estoque remoto</i>:)
899						,<br> produtoQtdeEstoque(Remoto):[{$_stockRemote}] {ATUALIZA} -> attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} > {{$attrStock}}] <br>";
900						$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$rTamanho);
901					
902						$variation_data = [
903							'attributes'  => [
904							'cor'     => $listCorT->produtoCor,
905							'tamanho' => $listCorT->produtoTamanho,
906							],
907							'ID'          	 => $cproducts,
908							'sku'            => MigrationRules::getProductTeste()->produtoId,
909							'update'         => true,
910							'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
911							'sale_price'  	 => MigrationRules::getProductTeste()->produtoPrecoPromo,
912							'stock_qty'      => $_stockRemote
913						];
914					// The function to be run
915						_create_product_variation(MigrationRules::getPostId(), $variation_data );
916						//self::$isUpdated = true;
917					
918										
919				}
920				if($_stockRemote < $attrStock){//se for diferente, atualiza com base no valor do estoque remoto
921					//atualiza
922					echo "produtoQtdeEstoque(Remoto):[{$_stockRemote}] {Menor do que Estoque Local - Ação: Incrementa Sobre o Stock Local o Estoque Remoto} -> attrStock(Estoque Local):[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} < {{$attrStock}}] <br>";
923					echo "<hr><hr>";
924					$localStk = (int)get_post_meta($cproducts, '_stock', true );
925					//var_dump($localStk);
926
927					$variation_data = [
928						'attributes'  => [
929						'cor'     => $listCorT->produtoCor,
930						'tamanho' => $listCorT->produtoTamanho,
931						],
932						'ID'          	 => $cproducts,
933						'sku'            => MigrationRules::getProductTeste()->produtoId,
934						'update'         => true,
935						'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
936						'sale_price'  	 => MigrationRules::getProductTeste()->produtoPrecoPromo,
937						'stock_qty'      => $_stockRemote + $localStk 
938					];
939				// The function to be run
940					_create_product_variation(MigrationRules::getPostId(), $variation_data );
941					//self::$isUpdated = true;
942
943				}
944			}elseif(($totalL)-1 == $c && $totalL < $rtotal){//se tamanhos são diferentes
945				// [se a quantidade de produtos com cores iguais e tamanhos diferentes
946				// _remotos_ forem maior que a quantidade de produtos locais (insere ou atualiza)
947				echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
948				$result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
949					['cor_key'=>'attribute_pa_cor',
950						'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
951					]);
952
953				//var_dump($result);
954				
955				if(empty($result)){
956				//var_dump($result);
957							// The variation data
958							echo "{Tamanho remoto não existe - Tamanho [{$rTamanho}] Será persistido} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
959							$variation_data = [
960								'attributes'  => [
961									'cor'     => $listCorT->produtoCor,
962									'tamanho' => $listCorT->produtoTamanho,
963								],
964								'sku'            => MigrationRules::getProductTeste()->produtoId,
965								'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
966								   'sale_price'     => MigrationRules::getProductTeste()->produtoPrecoPromo,
967								'stock_qty'      => $_stockRemote
968							];
969							// The function to be run
970							_create_product_variation(MigrationRules::getPostId(), $variation_data );
971				}
972				else{
973
974					echo "{Tamanho remoto existe na base [{$rTamanho}] Não Será atualizada} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | {$result[0]->ID} | STock:{$_stockRemote}<br>";
975					/*$variation_data = [
976						'attributes'  => [
977							'cor'     => $listCorT->produtoCor,
978								'tamanho' => $listCorT->produtoTamanho,
979								],
980								'ID'          	 => $cproducts,
981								'sku'            => MigrationRules::getProductTeste()->produtoId,
982								'update'         => true,
983								'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
984								'sale_price'  	 => MigrationRules::getProductTeste()->produtoPrecoPromo,
985								'stock_qty'      => $_stockRemote
986							];
987							*/
988							//_create_product_variation(MigrationRules::getPostId(), $variation_data );
989							
990													
991				}				
992			}
993			//se a quantidade do estoque for igual
994			//var_dump(substr($listCorT->produtoQtdeEstoque,0,1));
995			
996		}else{//atualiza $c (contador do loop das variacoes remotas)
997			$totalL = self::getTotalLocalProducts();
998			$diffProducts  = $rtotal-$totalL;
999			echo "#produtoCor:[{$pcor},{$rTamanho}] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total:{$rtotal}, diffP:{$diffProducts}) - variable_id:[$cproducts] | {Cor remota não existe em cores locais}<br>";
1000			//se total de variacoes locais é menor que o total de variacoes remotas
1001			//insere a variacao remota até a quantidade de variacoes locais ficar = a quantidade de variacoes
1002			//remotas
1003			//enquanto 29 <= 52 { execulta } 
1004			// $c < $rtotal && $z <= $rtotal && { $z = $c; store(color); $z++;}
1005			//$z = $c;
1006			//30 == $c
1007			//se o contador de produtos locais ficar com o mesmo valor do total de produtos locais tornarem iguais
1008			//e a quantidade de produtos locais for menor que o total de produtos remotos persiste o produto remoto
1009			if(($totalL)-1 == $c && $totalL < $rtotal){
1010			//if($z <= $rtotal){
1011			//$pID = MigrationRules::getPostId();
1012			//$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_cor',$pcor);
1013			//$resultT = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$listCorT->produtoTamanho);
1014			//echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1015			$result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1016				['cor_key'=>'attribute_pa_cor',
1017						'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1018			]);
1019
1020			echo "-produtoCor:[{$pcor}|[$rTamanho]] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c}[Último Produto Local],total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor remota não existe em cores locais} |<br>";
1021
1022			//var_dump($result);
1023			if(empty($result)){
1024				//var_dump($result);
1025							// The variation data
1026							echo "{Cor remota não existe - Cor [{$pcor}] Será persistida} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1027							$variation_data = [
1028								'attributes'  => [
1029									'cor'     => $listCorT->produtoCor,
1030									'tamanho' => $listCorT->produtoTamanho,
1031								],
1032								'sku'            => MigrationRules::getProductTeste()->produtoId,
1033								'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
1034								   'sale_price'     => MigrationRules::getProductTeste()->produtoPrecoPromo,
1035								'stock_qty'      => $_stockRemote
1036							];
1037							// The function to be run
1038							_create_product_variation(MigrationRules::getPostId(), $variation_data );
1039							//$z++;
1040			} 
1041			else{
1042				echo "*produtoCor:[{$pcor}|[$rTamanho]] existe como variacao local na base AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor/Tamanho remota existe em cores/tamanhos locais(Operacão: Não atualiza)} |<br>";
1043				//echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1044				$result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1045					['cor_key'=>'attribute_pa_cor',
1046						'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1047					]);
1048				//var_dump($result[0]->ID);
1049				
1050				//if(empty($result)){
1051				//var_dump($result);
1052							// The variation data
1053							echo "{Variaçao de tamanho Existe para a cor:{$pcor}  ->{Tamanho:{$listCorT->produtoTamanho}} - Variação de cor:[{$pcor}] Não Será Criada, pois já existe} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1054							$variation_data = [
1055								'attributes'  => [
1056									'cor'     => $listCorT->produtoCor,
1057									'tamanho' => $listCorT->produtoTamanho,
1058								],
1059								'sku'            => MigrationRules::getProductTeste()->produtoId,
1060								'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
1061								   'sale_price'     => MigrationRules::getProductTeste()->produtoPrecoPromo,
1062								'stock_qty'      => $_stockRemote
1063							];
1064							// The function to be run
1065							//_create_product_variation(MigrationRules::getPostId(), $variation_data );
1066				
1067								#
1068								//echo "{Cor remota existe - Cor [{$pcor}] Será Atualizada} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1069								/*
1070								$variation_data = [
1071									'attributes'  => [
1072										'cor'     => $listCorT->produtoCor,
1073										'tamanho' => $listCorT->produtoTamanho,
1074									],
1075									'ID'          	 => $cproducts,
1076									'sku'            => MigrationRules::getProductTeste()->produtoId,
1077									'update'         => true,
1078									'regular_price'  => MigrationRules::getProductTeste()->produtoPrecoBase,
1079									'sale_price'  	 => MigrationRules::getProductTeste()->produtoPrecoPromo,
1080									'stock_qty'      => $_stockRemote
1081								];
1082								// The function to be run
1083								_create_product_variation(MigrationRules::getPostId(), $variation_data );
1084								*/						
1085			}
1086			
1087			
1088		}else{
1089				//echo ">produtoCor:[{$pcor}] são diferentes AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts] | <br>";
1090			}
1091			
1092		}
1093		//exit;
1094	}
1095
1096	static function setTotalLocalProducts($lproduct){
1097		self::$lproduct = $lproduct;
1098	}
1099
1100	static function setTotalRemoteProducts($rproduct){
1101		self::$rproduct = $rproduct;
1102	}
1103
1104
1105	static function getTotalLocalProducts(){
1106		return self::$lproduct;
1107	}
1108
1109	static function getTotalRemoteProducts(){
1110		return self::$rproduct;
1111	}
1112
1113	static function setCollection($collection){
1114		self::$collection = $collection;
1115	}
1116
1117	static function getCollection(){
1118		return self::$collection;
1119	}
1120	
1121
1122	static function setPostId($postId){
1123		self::$postId = $postId;
1124	}
1125
1126	static function getPostId(){
1127		return self::$postId;
1128	}
1129
1130	static function setProdPosition($prodPosition){
1131		self::$prodPosition = $prodPosition;
1132	}
1133
1134	static function getProdPosition(){
1135		return self::$prodPosition;
1136	}
1137
1138	static function setProductTeste($productTeste){
1139		self::$productTeste = $productTeste;
1140	}
1141	//qualquer coisa excerto o numero 0.
1142	public static function onlyNumbers($str)
1143	{
1144    	$str = preg_replace('/[^0-9]+/', '', $str);
1145    	return $str;
1146	}
1147
1148	static function getProductTeste(){
1149		//self::$productTeste->produtoPrecoPromo = number_format(self::$productTeste->produtoPrecoPromo,2,",",".");
1150		//self::$productTeste->produtoPrecoBase = number_format(self::onlyNumbers(self::$productTeste->produtoPrecoBase),2,",",".");
1151		$wsprice = self::$productTeste->produtoPrecoBase;
1152		echo "<h3>preço literal do Ws: {$wsprice}</h3>";
1153
1154		$precoBase = self::onlyNumbers(rtrim(self::$productTeste->produtoPrecoBase, "0"));
1155		echo "<h3>preço base Manipulado: {$precoBase}</h3>";
1156		$precoBase = number_format((int)$precoBase,2,",",".");
1157
1158		$precoPromo = self::onlyNumbers(rtrim(self::$productTeste->produtoPrecoPromo,"0"));
1159		$precoPromo = number_format((int)$precoPromo,2,",",".");
1160
1161		self::$productTeste->produtoPrecoBase = $precoBase;
1162		self::$productTeste->produtoPrecoPromo = $precoPromo;
1163
1164		//$precoBase = substr(self::$productTeste->produtoPrecoBase,0,-2);
1165		echo "<h3>Preço final{$precoBase}</h3>";
1166		
1167		//var_dump($precoBase);
1168		//exit;
1169		
1170		return self::$productTeste;
1171	}
1172
1173	static function setRemoteAttr($remoteAttr){
1174		self::$remoteAttr = $remoteAttr;
1175	}
1176
1177	static function getRemoteAttr(){
1178		return self::$remoteAttr;
1179	}
1180	
1181}
1182
1183class FavelaMigration {
1184
1185	static function listAllVariableProducts($post_id){
1186		//cria uma instancia do produto
1187		$product = wc_get_product($post_id);
1188
1189		//pega todas as variacoes do produto (só os ids)
1190		if(!empty($product)){
1191			$current_products = $product->get_children();
1192			return(count($current_products));
1193		}
1194
1195	}
1196	
1197	static function getAllVariableProduct($post_id){
1198		//cria uma instancia do produto
1199		$product = wc_get_product($post_id);
1200		if(!empty($product)){
1201			$current_products = $product->get_children();
1202			return $current_products;
1203		}
1204	}
1205
1206	static function getAllRemoteVariableProduct(stdClass $collection){
1207		return(count($collection->listaCorTamanho));
1208	}
1209
1210	static function getAllRemoteVariableProductNames(stdClass $collection){
1211		foreach($collection->listaCorTamanho as $k=>$coll){
1212			echo "{$coll->produtoCor},{$coll->produtoTamanho} -({$k})<br>";
1213		}
1214	}
1215
1216
1217	static function getAttributesForProduct(stdClass $product){
1218		foreach($product->listaCorTamanho as $p=>$prop){
1219			$cores[] = $prop->produtoCor;
1220			$tamanho[] = $prop->produtoTamanho;
1221			$stock[] = $prop->produtoQtdeEstoque; 
1222		}
1223
1224		return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1225	}
1226
1227	static function _getAttributesForProduct(stdClass $product){
1228		//echo "<h1>Objeto Remoto como stdClass: </h1>";
1229		//var_dump($product->listaCorTamanho);
1230		$c = 0;
1231		foreach($product->listaCorTamanho as $p=>$prop){
1232			//$object = $object[$k];
1233			foreach($prop as $k=>$value){
1234				//$attributeMeta[] = $prop->$k;
1235				//$object[] = ["{$k}"=>[$prop->$k]];
1236				//echo "p:[{$p}] k:[{$k}] count:[{$c}] value:[{$value}]<br>";
1237				$attribute = substr($k,7);//produto{AttrName}elimina produto da str
1238				if("QtdeEstoque" != $attribute && "CorHex" != $attribute && "CorId" != $attribute){
1239					$object[$attribute][] = $product->listaCorTamanho[$p]->$k;
1240				}
1241				
1242			}
1243			//echo "<h3>{$product->listaCorTamanho[$p]->$attribute} [{$attribute}]</h3>";	
1244			$c++;
1245		}
1246		
1247		//var_dump($object);
1248
1249		return $object;
1250		//return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1251	}
1252
1253	static function getAllAttributes($post_id){
1254		//exibe os atributos do produto		
1255		$prodAttrGlobal = get_post_meta($post_id, '_product_attributes', true );
1256		echo "<h2>Atributos do produto</h2>";
1257		var_dump($prodAttrGlobal);
1258	}
1259
1260	static function getAllAttrForTaxonomy($tax,$post_id){
1261		echo "<h2>termos dos atributos dos produtos(pa_tamanho)tax:{$tax}| id:{$post_id}</h2>";
1262		$result = wc_get_product_terms($post_id, $tax, 'names');
1263		var_dump($result);
1264	}
1265	
1266	static function updateVariableProduct(stdClass $productTeste, array $current_products){
1267		//counters
1268		MigrationRules::setTotalLocalProducts(count($current_products));
1269		MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1270
1271		$x = 0; $c=0;
1272		//loop (produto remoto / produtos variavies)
1273		foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1274			foreach($current_products as $c=>$cproducts){
1275				$attrCor = get_post_meta($cproducts, 'attribute_pa_cor', true );
1276				var_dump($attrCor);
1277				$attrTamanho = get_post_meta($cproducts, 'attribute_pa_tamanho', true );
1278				$attrStock = get_post_meta($cproducts, '_stock', true );
1279				//atualiza estoque
1280				MigrationRules::updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts);
1281				$x++;//no loop das variacoes locais ($current_products)
1282			}
1283			$c++;//no loop das variacoes remotas ($productTest)
1284		}
1285	}
1286
1287
1288	static function storeVariableProduct(stdClass $productTeste){
1289		//counters
1290		MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1291		$c=0;
1292		//loop (produto remoto / produtos variavies)
1293		foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1294			MigrationRules::storeStock($listCorT, $c);
1295			$c++;//no loop das variacoes remotas ($productTest)
1296		}
1297	}
1298
1299	static function searchProduct($productTeste){
1300		$result = get_wc_product_by_title($productTeste->produtoNome, $productTeste->produtoMarca);
1301		return $result;
1302	}
1303
1304	static function getAllLocalProducts(){
1305		// Get 10 most recent product IDs in date descending order.
1306		$query = new WC_Product_Query( array(
1307    		'limit' => 209,
1308    		'orderby' => 'date',
1309    		'order' => 'ASC',
1310		));
1311		
1312		//echo "query aqui";
1313		//var_dump($query);
1314		$products = $query->get_products();
1315		//var_dump($products);
1316		return $products;
1317	}
1318
1319	static function init($prodPosition){
1320		//recebe uma coleção remota
1321		$collection = getProdutosForWikiWs();
1322		$productTeste = $collection[$prodPosition];
1323		//se colecao for vazia sai do funcao 
1324		if(empty($productTeste)){
1325			return;
1326		}
1327
1328		//Busca com base no {titulo}, {nomeDaMarca} na base da loja
1329		//caso exista um produto local com o mesmo nome de um produto remoto.
1330		$resultSearch = self::searchProduct($productTeste);
1331		
1332		if(empty($resultSearch)){
1333			echo "<h4>Produto não existe na base Local</h4>";
1334			$pRemotosQNaoExistemLocal[] = $productTeste->produtoNome;
1335		}else{
1336			$totalIds[] = $resultSearch->get_id();
1337			echo "<h4>Produto existe na base Local</h2>";
1338			//var_dump($resultSearch); 
1339		}
1340
1341		$pRemotos = self::getAllRemoteVariableProduct($productTeste);
1342		echo "<h2>Total de produtos Variáveis Remotos: {updated}<i>[{$pRemotos}]</i></h2>";
1343		//todos os nomes das variáveis remotas
1344		self::getAllRemoteVariableProductNames($productTeste);
1345		
1346		//busca os produtos locais baseados no sku = WebService.produtoTest.id
1347		$post_id = wc_get_product_id_by_sku($productTeste->produtoId);
1348
1349		//caso 
1350		/*if(!empty($post_id)){
1351			update_post_meta($post_id, '_sku', $productTeste->produtoId, true);
1352			echo "<h2>SKU do produto Manipulado</h2><br>";
1353			var_dump($post_id);
1354		}*/
1355		//var_dump($produtoTeste);
1356		//pega os atributosdo produto remoto (taxonomias e termos)
1357		//$remoteAttributes = self::getAttributesForProduct($productTeste);
1358		$remoteAttributes = self::_getAttributesForProduct($productTeste);
1359		echo "<h1>Array de atributos remotos construido:</h1>";
1360		var_dump($remoteAttributes);
1361
1362		if($post_id != 0){
1363			update_product_variation( array(
1364				'ID'			=> $post_id,
1365				'author'        => '', // optional
1366					'title'         => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
1367				'content'       => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao}  - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1368				'excerpt'       => $productTeste->produtoDescricao,
1369				'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1370				'sale_price'    => $productTeste->produtoPrecoPromo, // product sale price (optional)
1371				'stock'         => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1372				'manager_stock' => '0',
1373				'category'		=> $productTeste->produtoCat,
1374					// Set a minimal stock quantity
1375				'image_id'      => '', // optional
1376				'gallery_ids'   => array(), // optional
1377				'sku'           => $productTeste->produtoId, // optional
1378				'tax_class'     => '', // optional
1379				'weight'        => $productTeste->produtoPeso, // optional
1380				'width'         => $productTeste->produtoDimensaoL,
1381				'length'        => $productTeste->produtoDimensaoC,
1382				// For NEW attributes/values use NAMES (not slugs)
1383				'attributes'    => [
1384					'Cor'   =>  $remoteAttributes['Cor'],
1385					'Tamanho'   =>  $remoteAttributes['Tamanho']
1386				],
1387				));
1388		}else{
1389			//var_dump($produtoTeste);
1390			$post_id = update_product_variation( array(
1391				'author'        => '', // optional
1392					'title'         => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
1393				'content'       => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao}  - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1394				'excerpt'       => $productTeste->produtoDescricao,
1395				'category'		=> $productTeste->produtoCat,
1396				'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1397				'sale_price'    => $productTeste->produtoPrecoPromo, // product sale price (optional)
1398				'stock'         => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1399				'manager_stock' => '0',
1400					// Set a minimal stock quantity
1401				'image_id'      => '', // optional
1402				'gallery_ids'   => array(), // optional
1403				'sku'           => $productTeste->produtoId, // optional
1404				'tax_class'     => '', // optional
1405				'weight'        => $productTeste->produtoPeso, // optional
1406				'width'         => $productTeste->produtoDimensaoL,
1407				'length'        => $productTeste->produtoDimensaoC,
1408				// For NEW attributes/values use NAMES (not slugs)
1409				'attributes'    => ['Cor'   =>  $remoteAttributes['Cor'],
1410				'Tamanho'   =>  $remoteAttributes['Tamanho']]
1411				) );
1412		}	
1413		//exit;
1414		
1415		//lista todos os produtos variáveis.
1416		echo "<h1>Total de Variações Locais</h1>";
1417		var_dump(self::listAllVariableProducts($post_id));
1418
1419		//exibe todos os attributos
1420		self::getAllAttributes($post_id);
1421		
1422		//exibe todos os termos (por taxonomia)
1423		self::getAllAttrForTaxonomy($tax='pa_cor',$post_id);
1424
1425		//retorna um array contendo todos os ids de produtos variáveis
1426		$current_products = self::getAllVariableProduct($post_id);
1427		//atualiza a loja com base nas informacoes dos produtos variaveis do WS
1428		MigrationRules::setCollection($collection);
1429		MigrationRules::setPostId($post_id);
1430		MigrationRules::setProdPosition($prodPosition);
1431		MigrationRules::setProductTeste($productTeste);
1432		MigrationRules::setRemoteAttr($remoteAttributes);
1433		
1434		//post_id, $collection, prodposition, productTeste, remoteAttr
1435		if(empty($current_products)){
1436			self::storeVariableProduct($productTeste);	
1437		}
1438		else{
1439			self::updateVariableProduct($productTeste,$current_products);
1440		}
1441
1442
1443	}
1444}
1445
1446function createTerms($post_id, $attributes_data){
1447	if( sizeof($attributes_data) > 0 ){
1448    $attributes = array(); // Initializing
1449	
1450    // Loop through defined attribute data
1451    foreach( $attributes_data as $key => $attribute_array ) {
1452        if( isset($attribute_array['name']) && isset($attribute_array['options']) ){
1453            // Clean attribute name to get the taxonomy
1454            $taxonomy = 'pa_' . wc_sanitize_taxonomy_name( $attribute_array['name'] );
1455
1456            $option_term_ids = array(); // Initializing
1457
1458            // Loop through defined attribute data options (terms values)
1459            foreach( $attribute_array['options'] as $option ){
1460                if( term_exists( $option, $taxonomy ) ){			
1461                    // Save the possible option value for the attribute which will be used for variation later
1462                    wp_set_object_terms($post_id, $option, $taxonomy, true );
1463                    // Get the term ID
1464                    $option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1465                }else{
1466					//wp_set_object_terms($post_id, $option, $taxonomy, true );
1467					//$option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1468					//var_dump($option_term_ids);
1469				}
1470            }
1471		}
1472
1473        // Loop through defined attribute data
1474        $attributes[$taxonomy] = array(
1475            'name'          => $taxonomy,
1476            'value'         => $option_term_ids, // Need to be term IDs
1477            'position'      => $key + 1,
1478            'is_visible'    => $attribute_array['visible'],
1479            'is_variation'  => $attribute_array['variation'],
1480            'is_taxonomy'   => '1'
1481        );
1482    }
1483    // Save the meta entry for product attributes
1484    update_post_meta( $post_id, '_product_attributes', $attributes);
1485
1486	}
1487}
1488
1489function create_product_attribute( $label_name ){
1490    global $wpdb;
1491
1492    $slug = sanitize_title( $label_name );
1493
1494    if ( strlen( $slug ) >= 28 ) {
1495        return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
1496    } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
1497        return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
1498    } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
1499        return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Name "%s" is already in use. Change it, please.', 'woocommerce' ), $label_name ), array( 'status' => 400 ) );
1500    }
1501
1502    $data = array(
1503        'attribute_label'   => $label_name,
1504        'attribute_name'    => $slug,
1505        'attribute_type'    => 'select',
1506        'attribute_orderby' => 'menu_order',
1507        'attribute_public'  => 0, // Enable archives ==> true (or 1)
1508    );
1509
1510    $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );
1511
1512    if ( is_wp_error( $results ) ) {
1513        return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
1514    }
1515
1516    $id = $wpdb->insert_id;
1517
1518    do_action('woocommerce_attribute_added', $id, $data);
1519
1520    wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
1521
1522    delete_transient('wc_attribute_taxonomies');
1523}
1524
1525/**
1526 * Save a new product attribute from his name (slug).
1527 *
1528 * @since 3.0.0
1529 * @param string $name  | The product attribute name (slug).
1530 * @param string $label | The product attribute label (name).
1531 */
1532function save_product_attribute_from_name( $name, $label='', $set=true ){
1533    if( ! function_exists ('get_attribute_id_from_name') ) return;
1534
1535    global $wpdb;
1536
1537    $label = $label == '' ? ucfirst($name) : $label;
1538    $attribute_id = get_attribute_id_from_name( $name );
1539
1540    if( empty($attribute_id) ){
1541        $attribute_id = NULL;
1542    } else {
1543        $set = false;
1544    }
1545    $args = array(
1546        'attribute_id'      => $attribute_id,
1547        'attribute_name'    => $name,
1548        'attribute_label'   => $label,
1549        'attribute_type'    => 'select',
1550        'attribute_orderby' => 'menu_order',
1551        'attribute_public'  => 0,
1552    );
1553
1554    if( empty($attribute_id) ) {
1555        $wpdb->insert(  "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
1556        set_transient( 'wc_attribute_taxonomies', false );
1557    }
1558
1559    if( $set ){
1560        $attributes = wc_get_attribute_taxonomies();
1561        $args['attribute_id'] = get_attribute_id_from_name( $name );
1562        $attributes[] = (object) $args;
1563        //print_r($attributes);
1564        set_transient( 'wc_attribute_taxonomies', $attributes );
1565    } else {
1566        return;
1567    }
1568}
1569
1570/**
1571 * Get the product attribute ID from the name.
1572 *
1573 * @since 3.0.0
1574 * @param string $name | The name (slug).
1575 */
1576function get_attribute_id_from_name( $name ){
1577    global $wpdb;
1578    $attribute_id = $wpdb->get_col("SELECT attribute_id
1579    FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
1580    WHERE attribute_name LIKE '$name'");
1581    return reset($attribute_id);
1582}
1583
1584/**
1585 * Create a new variable product (with new attributes if they are).
1586 * (Needed functions:
1587 *
1588 * @since 3.0.0
1589 * @param array $data | The data to insert in the product.
1590 */
1591
1592function create_product_variation( $data ){
1593    if( ! function_exists ('save_product_attribute_from_name') ) return;
1594
1595    $postname = sanitize_title( $data['title'] );
1596    $author = empty( $data['author'] ) ? '1' : $data['author'];
1597
1598    $post_data = array(
1599        'post_author'   => $author,
1600        'post_name'     => $postname,
1601        'post_title'    => $data['title'],
1602        'post_content'  => $data['content'],
1603        'post_excerpt'  => $data['excerpt'],
1604        'post_status'   => 'publish',
1605        'ping_status'   => 'closed',
1606		'post_type'     => 'product_variation',
1607		'post_parent'   => $data['parent_id'],
1608        'guid'          => home_url( '/product/'.$postname.'/' ),
1609	);
1610	
1611    // Creating the product (post data)
1612    //$product_id = wp_insert_post(  );
1613	$result = wp_insert_post( $post_data );
1614
1615	if ( $result && ! is_wp_error( $result ) ) {
1616		$product_id = $result;
1617		// Do something else
1618		var_dump($result);
1619		echo "sucesso";
1620	}else{
1621		echo "erro ao gravar produto variavel";
1622		var_dump($result);
1623	}
1624    // Get an instance of the WC_Product_Variable object and save it
1625    $product = new WC_Product_Variation( $product_id );
1626    
1627    ## ---------------------- Other optional data  ---------------------- ##
1628    ##     (see WC_Product and WC_Product_Variable setters methods)
1629
1630    // THE PRICES (No prices yet as we need to create product variations)
1631
1632	// IMAGES GALLERY
1633	// Prices
1634    if( empty( $data['sale_price'] ) ){
1635        $product->set_price( $data['regular_price'] );
1636    } else {
1637        $product->set_price($data['sale_price'] );
1638        $product->set_sale_price($data['sale_price'] );
1639    }
1640    $variation->set_regular_price($data['regular_price'] );
1641
1642    if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
1643        $product->set_gallery_image_ids( $data['gallery_ids'] );
1644
1645    // SKU/*
1646//    if( ! empty( $data['sku'] ) )
1647  //      $product->set_sku( $data['sku'] );
1648
1649			
1650    // STOCK (stock will be managed in variations)
1651	$product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
1652	if($data['manager_stock'] == '0'){
1653		$product->set_manage_stock(false);
1654	}else{
1655		$product->set_manage_stock(true);
1656	}
1657    
1658    $product->set_stock_status('');
1659
1660    // Tax class
1661    if( empty( $data['tax_class'] ) )
1662        $product->set_tax_class( $data['tax_class'] );
1663
1664    // WEIGHT
1665    if( ! empty($data['weight']) )
1666        $product->set_weight(''); // weight (reseting)
1667    else
1668        $product->set_weight($data['weight']);
1669	
1670	$product->validate_props(); // Check validation
1671	
1672    ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
1673
1674    $product_attributes = array();
1675
1676    foreach( $data['attributes'] as $key => $terms ){
1677        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
1678        $attr_label = ucfirst($key); // attribute label name
1679        $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
1680
1681        // NEW Attributes: Register and save them
1682		if( ! taxonomy_exists( $taxonomy ) )
1683			
1684            var_dump(save_product_attribute_from_name( $attr_name, $attr_label ));
1685
1686        $product_attributes[$taxonomy] = array (
1687            'name'         => $taxonomy,
1688            'value'        => '',
1689            'position'     => '',
1690            'is_visible'   => 0,
1691            'is_variation' => 1,
1692            'is_taxonomy'  => 1
1693        );
1694
1695        foreach( $terms as $value ){
1696            $term_name = ucfirst($value);
1697            $term_slug = sanitize_title($value);
1698
1699            // Check if the Term name exist and if not we create it.
1700            if( ! term_exists( $value, $taxonomy ) )
1701                wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
1702
1703            // Set attribute values
1704            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
1705        }
1706    }
1707	update_post_meta( $product_id, '_product_attributes', $product_attributes );
1708	
1709    $product->save(); // Save the data
1710}
1711
1712function get_product_category($catname){
1713	if($catname == ''){
1714		$catname = "CAMISAS";
1715	}else{
1716		$catnamesub = $catname;
1717		$slug = $catnamesub;
1718		//var_dump($slug);
1719		$productCategory = get_term_by( 'name', $slug, 'product_cat' );
1720		
1721		//echo "termo Id";
1722		//var_dump($productCategory->term_id);
1723		if($productCategory){
1724			$cat_id = get_term_by('id',$productCategory->term_id , 'product_cat' );
1725		}else{
1726			return false;
1727		}
1728		//$cat_id = get_category($productCategory->term_id);
1729		//echo "cat_id";
1730		//var_dump($cat_id);
1731	}
1732	
1733	if(empty($cat_id)) {
1734		//echo "insere um termo se não existir a categoria<br>";
1735		//var_dump($cat_id);
1736		$arg = array( 'description' => $slug, 'parent' => 0 );
1737		$cat_id = wp_insert_term($slug, "product_cat", $arg);
1738		//echo "id inserido da categoria criada<br>";
1739		//var_dump($cat_id);
1740		return $cat_id['term_id'];
1741	}else{
1742		//var_dump("retornando resultado existindo uma categoria correspondente");
1743		return $cat_id->term_id;
1744	}
1745}
1746/**
1747 * Update a new variable product (with new attributes if they are).
1748 * (Needed functions:
1749 *
1750 * @since 3.0.0
1751 * @param array $data | The data to insert in the product.
1752 */
1753function update_product_variation($data){
1754	if( ! function_exists ('save_product_attribute_from_name') ) return;
1755	
1756	$category_id = get_product_category($data['category']);
1757	$postname = sanitize_title( $data['title'] );
1758	$author = empty( $data['author'] ) ? '1' : $data['author'];
1759
1760	if(empty($data['excerpt'])){
1761		$data['excerpt'] = $postname;
1762	}
1763	
1764
1765	if(empty($data['ID'])){
1766
1767		$post_data = array(
1768			'post_author'   => $author,
1769			'post_name'     => $postname,
1770			'post_title'    => $data['title'],
1771			'post_content'  => $data['content'],
1772			'post_excerpt'  => $data['excerpt'],
1773			'post_status'   => 'publish',
1774			'ping_status'   => 'closed',
1775			'post_type'     => 'product',
1776			'guid'          => home_url( '/product/'.$postname.'/') ,
1777			'tax_input'  => ['product_cat' => $category_id]
1778		);
1779
1780		$product_id = wp_insert_post( $post_data );
1781		//wp_set_post_terms($product_id, get_term()->slug,'product_cat',true);
1782	}else{
1783
1784		if(!isset($data['insert_variable_product_unique'])){
1785			$post_data = array(
1786				'ID'            => $data['ID'],
1787				'post_author'   => $author,
1788				'post_name'     => $postname,
1789				'post_title'    => $data['title'],
1790				'post_content'  => $data['content'],
1791				'post_excerpt'  => $data['excerpt'],
1792				'post_status'   => 'publish',
1793				'ping_status'   => 'closed',
1794				'post_type'     => 'product',
1795				'guid'          => home_url( '/product/'.$postname.'/' ),
1796				'tax_input'     =>  ['product_cat'=>$category_id]
1797			);
1798			$product_id = wp_update_post( $post_data );
1799		}
1800
1801	}
1802	
1803	$product = new WC_Product_Variable( $product_id );
1804	$product->save();
1805
1806    ## ---------------------- Other optional data  ---------------------- ##
1807    ##     (see WC_Product and WC_Product_Variable setters methods)
1808
1809    //THE PRICES (No prices yet as we need to create product variations)
1810    //IMAGES GALLERY
1811    if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
1812        $product->set_gallery_image_ids( $data['gallery_ids'] );
1813
1814    //SKU
1815    if( ! empty( $data['sku'] ) )
1816        $product->set_sku( $data['sku'] );
1817
1818    // STOCK (stock will be managed in variations)
1819	$product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
1820	if($data['manager_stock'] == '0'){
1821		$product->set_manage_stock(false);
1822	}else{
1823		$product->set_manage_stock(true);
1824	}
1825    
1826    $product->set_stock_status('');
1827
1828    // Tax class
1829    if( empty( $data['tax_class'] ) )
1830        $product->set_tax_class( $data['tax_class'] );
1831
1832    // WEIGHT
1833    if( ! empty($data['weight']) )
1834        $product->set_weight(''); // weight (reseting)
1835    else
1836		$product->set_weight($data['weight']);
1837		
1838	//length
1839	if( ! empty($data['length']) )
1840        $product->set_length(''); // length (reseting)
1841    else
1842		$product->set_length($data['length']);
1843			
1844	$product->validate_props(); // Check validation
1845	
1846	//WIDTH
1847	if( ! empty($data['width']) )
1848	$product->set_width(""); // weight (reseting)
1849else
1850	$product->set_width($data['width']);
1851
1852    ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
1853
1854    $product_attributes = array();
1855	echo "Atributes da persistência do Objeto (não da variação)";
1856	var_dump($data['attributes']);
1857
1858    foreach( $data['attributes'] as $key => $terms ){
1859        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
1860        $attr_label = ucfirst($key); // attribute label name
1861        $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
1862
1863        // NEW Attributes: Register and save them
1864		if( ! taxonomy_exists( $taxonomy ) )
1865			echo "salvando taxonomia: name:{$attr_name}, label:{$attr_label}, tax:{$taxonomy} <br>";
1866			var_dump(save_product_attribute_from_name( $attr_name, $attr_label ));
1867			//$slug = 'pa_' . strtolower($attribute->name);
1868			$attribute_id = wc_create_attribute( array(
1869				'name'         => $attr_label,
1870				'slug'         => $attr_name,
1871				'type'         => 'product',
1872				'order_by'     => 'menu_order',
1873				'has_archives' => false,
1874			) );
1875			
1876			var_dump($attribute_id);
1877			//Register it as a wordpress taxonomy for just this session. Later on this will be loaded from the woocommerce taxonomy table.
1878			/*register_taxonomy(
1879				$taxonomy,
1880				apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy, array( 'product' ) ),
1881				apply_filters( 'woocommerce_taxonomy_args_' . $taxonomy, array(
1882					'labels'       => array(
1883						'name' => $attr_label,
1884					),
1885					'hierarchical' => true,
1886					'show_ui'      => false,
1887					'query_var'    => true,
1888					'rewrite'      => false,
1889				) )
1890			);*/
1891
1892
1893        $product_attributes[$taxonomy] = array (
1894            'name'         => $taxonomy,
1895            'value'        => '',
1896            'position'     => '',
1897            'is_visible'   => 0,
1898            'is_variation' => 1,
1899            'is_taxonomy'  => 1
1900        );
1901
1902        foreach( $terms as $value ){
1903            $term_name = ucfirst($value);
1904            $term_slug = sanitize_title($value);
1905			
1906            // Check if the Term name exist and if not we create it.
1907			if( ! term_exists( $value, $taxonomy ) )
1908				echo "salvando termo: term_name:{$term_name} | tax:{$taxonomy} | slug:{$term_slug}<br>";
1909                var_dump(wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) )); // Create the term
1910
1911			// Set attribute values
1912			if(isset($data['insert_variable_product_unique'])){
1913				echo "setando valores dos atributos: id:{$data['ID']}(atualizando), tax:{$taxonomy}, term_name:{$term_name}<br>";
1914				var_dump(wp_set_post_terms( $data['ID'], $term_name, $taxonomy, true ));
1915			}else{
1916				echo "setando valores dos atributos: id:{$product_id}(inserindo), tax:{$taxonomy}, term_name:{$term_name}<br>";
1917				var_dump(wp_set_post_terms( $product_id, $term_name, $taxonomy, true ));
1918			}
1919            
1920        }
1921	}
1922	//print_r($product);
1923	if(isset($data['insert_variable_product_unique'])){
1924		echo "atualizando: product Attrb: {$product_attributes}<br>";
1925		update_post_meta( $data['ID'], '_product_attributes', $product_attributes );
1926	}else{
1927		echo "inserindo: product Attrb:<br>";
1928		var_dump($product_attributes);
1929		update_post_meta( $product_id, '_product_attributes', $product_attributes );
1930	}	
1931	//var_dump($product);
1932	//exit;
1933	$product->save(); // Save the data
1934	return $product_id;
1935}
1936/*
1937*
1938$parent_id = 746; // Or get the variable product id dynamically
1939
1940// The variation data
1941$variation_data =  array(
1942    'attributes' => array(
1943        'size'  => 'M',
1944        'color' => 'Green',
1945    ),
1946    'sku'           => '',
1947    'regular_price' => '22.00',
1948    'sale_price'    => '',
1949    'stock_qty'     => 10,
1950);
1951
1952// The function to be run
1953create_product_variation( $parent_id, $variation_data );
1954*/
1955/**
1956 * Create a product variation for a defined variable product ID.
1957 *
1958 * @since 3.0.0
1959 * @param int   $product_id | Post ID of the product parent variable product.
1960 * @param array $variation_data | The data to insert in the product.
1961 */
1962
1963function _create_product_variation( $product_id, $variation_data ){
1964    // Get the Variable product object (parent)
1965	$product = wc_get_product($product_id);
1966	
1967	// Creating the product variation
1968	if(empty($variation_data['update'])){
1969		//var_dump($variation_data);
1970		$variation_post = array(
1971			'post_title'  => MigrationRules::getProductTeste()->produtoNome,
1972			'post_name'   => 'product-'. MigrationRules::getPostId() .'-variation',
1973			'post_status' => 'publish',
1974			'post_parent' => MigrationRules::getPostId(),
1975			'post_type'   => 'product_variation',
1976			'guid'        => site_url() . "/" . MigrationRules::getPostId()
1977		);
1978
1979		$variation_id = wp_insert_post( $variation_post );
1980	}else{
1981
1982		$variation_post = array(
1983			'ID'          => $variation_data['ID'],
1984			'post_title'  => $product->get_name(),
1985			'post_name'   => 'product-'.$product_id.'-variation',
1986			'post_status' => 'publish',
1987			'post_parent' => $product_id,
1988			'post_type'   => 'product_variation',
1989			'guid'        => $product->get_permalink()
1990		);
1991
1992		$variation_id = wp_update_post( $variation_post );
1993	}
1994	
1995
1996
1997    // Get an instance of the WC_Product_Variation object
1998    $variation = new WC_Product_Variation( $variation_id );
1999	//var_dump($variation_id);
2000	//exit;
2001	echo "Registrando taxonomia<br>";
2002	var_dump($variation_data['attributes']);
2003
2004    foreach ($variation_data['attributes'] as $attribute => $term_name )
2005    {
2006
2007        $taxonomy = 'pa_'.$attribute; // The attribute taxonomy
2008		
2009		echo "taxonomia problemática: {$taxonomy}<br>";
2010
2011        // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
2012        if( ! taxonomy_exists( $taxonomy ) ){
2013			echo "Registrando taxonomia : {$attribute}<br>";
2014            register_taxonomy(
2015                $taxonomy,
2016               'product_variation',
2017                array(
2018                    'hierarchical' => false,
2019                    'label' => ucfirst( $attribute ),
2020                    'query_var' => true,
2021                    'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
2022                )
2023            );
2024		}
2025
2026		$ntax = ucfirst( $attribute );
2027		echo "taxonomia com ucfirst: {$ntax}<br>";
2028		echo "nome do termo";
2029		var_dump($term_name);
2030
2031        // Check if the Term name exist and if not we create it.
2032		if( ! term_exists( $term_name, $taxonomy ) )
2033			echo "TERMO INSERIDO {$term_name}<br> ";
2034            var_dump(wp_insert_term( $term_name, $taxonomy )); // Create the term
2035
2036        $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug
2037
2038        // Get the post Terms names from the parent variable product.
2039        $post_term_names =  wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
2040
2041        // Check if the post term exist and if not we set it in the parent variable product.
2042        if( ! in_array( $term_name, $post_term_names ) )
2043		echo "wp_set_post_terms: nome do slug {$term_slug} | productId:{$product_id} | term_name:{$term_name} | tax:{$taxonomy}<br>";
2044			var_dump(wp_set_post_terms( $product_id, $term_name, $taxonomy, true ));
2045			
2046			//var_dump($term_slug);
2047		// Set/save the attribute data in the product variation
2048		echo "update_post_meta: variation_id: [{$variation_id}] - " . 'attribute_'.$taxonomy . "<br>";
2049        var_dump(update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug, true));
2050    }
2051
2052	## Set/save all other data
2053	
2054
2055    // SKU
2056    //if( ! empty( $variation_data['sku'] ) )
2057    //    $variation->set_sku( $variation_data['sku'] );
2058	
2059    // Prices
2060// Prices
2061echo "<h4>valores do preço promocional</h4><br>";
2062var_dump($variation_data['sale_price'] == "0,00");
2063var_dump($variation_data['sale_price']);
2064
2065if( empty( $variation_data['sale_price'] ) ){
2066		
2067	$variation->set_price( $variation_data['regular_price'] );
2068} else {
2069	if(!$variation_data['sale_price'] == "0,00"){
2070		$variation->set_sale_price( $variation_data['sale_price']);	
2071	}	
2072	$variation->set_price($variation_data['regular_price']);
2073}
2074$variation->set_regular_price( $variation_data['regular_price'] );
2075
2076	// Stock
2077	var_dump($variation_data['stock_qty']);
2078    if( ! empty($variation_data['stock_qty']) ){
2079        $variation->set_stock_quantity( $variation_data['stock_qty'] );
2080        $variation->set_manage_stock(true);
2081        $variation->set_stock_status('');
2082    } else {
2083        //$variation->set_manage_stock(true);
2084        $variation->set_manage_stock(false);
2085		$variation->set_stock_status('outofstock');
2086    }
2087    
2088    if($variation_data['stock_qty'] == 0){
2089		$variation->set_manage_stock(false);
2090		$variation->set_stock_status('outofstock');
2091	}
2092    $variation->set_weight(''); // weight (reseting)
2093	//var_dump( $variation_data['ID']);
2094	$variation->save(); // Save the data
2095	//var_dump($variation->get_stock_quantity());
2096	//exit;
2097}
2098
2099function tirarAcentos($string){
2100    return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string);
2101}
2102
2103/**
2104 * Method to delete Woo Product
2105 * 
2106 * @param int $id the product ID.
2107 * @param bool $force true to permanently delete product, false to move to trash.
2108 * @return \WP_Error|boolean
2109 */
2110function wh_deleteProduct($id, $force = FALSE)
2111{
2112    $product = wc_get_product($id);
2113	
2114    if(empty($product))
2115        return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce'), 'product', $id));
2116
2117    // If we're forcing, then delete permanently.
2118    if ($force)
2119    {
2120        if ($product->is_type('variable'))
2121        {
2122            foreach ($product->get_children() as $child_id)
2123            {
2124                $child = wc_get_product($child_id);
2125                $child->delete(true);
2126            }
2127        }
2128        elseif ($product->is_type('grouped'))
2129        {
2130            foreach ($product->get_children() as $child_id)
2131            {
2132                $child = wc_get_product($child_id);
2133                $child->set_parent_id(0);
2134                $child->save();
2135            }
2136        }
2137
2138        $product->delete(true);
2139        $result = $product->get_id() > 0 ? false : true;
2140    }
2141    else
2142    {
2143        $product->delete();
2144        $result = 'trash' === $product->get_status();
2145    }
2146
2147    if (!$result)
2148    {
2149        return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
2150    }
2151
2152    // Delete parent product transients.
2153    if ($parent_id = wp_get_post_parent_id($id))
2154    {
2155        wc_delete_product_transients($parent_id);
2156    }
2157    return true;
2158}
2159
2160/**
2161 * Add a widget to the dashboard.
2162 *
2163 * This function is hooked into the 'wp_dashboard_setup' action below.
2164 */
2165function wporg_add_dashboard_widgets() {
2166    wp_add_dashboard_widget(
2167        'wporg_dashboard_widget',                          // Widget slug.
2168        esc_html__( 'Wiki Importer', 'wporg' ), // Title.
2169        'wporg_dashboard_widget_render'                    // Display function.
2170    ); 
2171}
2172add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );
2173 
2174/**
2175 * Create the function to output the content of our Dashboard Widget.
2176 */
2177function wporg_dashboard_widget_render() {
2178	// Display whatever you want to show.
2179
2180	$html = '<h2>Clique <span style="color:#0099FF" id="importData"><b>aqui</b></span> para importar Dados do ERP Wiki</h2>
2181	<p id="link_produtos">Visualizar Produtos -> <a href="edit.php?post_type=product">aqui</a> </p>
2182	<div id="importBlock">
2183	    <img id="importLogo" width="450" height="368" src="https://lindabrand.com.br/wp-content/uploads/importLogo.png"/>
2184	</div>';
2185	
2186	$html .= '<script>
2187	jQuery("#link_produtos").hide();
2188	jQuery("#importData").click(function(){
2189
2190		jQuery.ajax({
2191			type: "GET",
2192			url: "admin.php?action=executeWikiImport",
2193			beforeSend: function(){
2194			jQuery("#importLogo").hide();
2195			var img = jQuery("<img />", { 
2196				id: "importGif",
2197				src: "https://lindabrand.com.br/wp-content/uploads/import.gif",
2198				width: "420px",
2199				height: "368",
2200				alt: "import"
2201			  });
2202
2203			  img.appendTo(jQuery("#importBlock"));
2204			},
2205			success: function(){
2206				alert("Dados Importados com sucesso");
2207				jQuery("#importGif").hide();
2208				jQuery("#importLogo").show();
2209				jQuery("#link_produtos").show();
2210			}
2211		});
2212	});
2213
2214	</script>';
2215
2216    echo $html;
2217}
2218
2219
2220
2221//add_action( 'importInitializer', 'executeWikiImport', 10,0);
2222//add_action("after_setup_theme",function(){
2223//	do_action('importInitializer');
2224//});
2225
2226
2227add_action( 'admin_init', 'executeWikiImport' );
2228function executeWikiImport(){
2229	if(isset($_GET['action']) && $_GET['action']=="executeWikiImport"){
2230		initMigration();
2231		//initMigration();
2232		//create curl resource
2233		//$ch = curl_init();
2234		//curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2235		//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2236		//$output = curl_exec($ch);
2237		//curl_close($ch);  
2238	}
2239}
2240
2241
2242add_action( 'woocommerce_thankyou', 'MyPersistRemoteObject3', 20, 2 );
2243function MyPersistRemoteObject3($order_id){
2244
2245	$ch = curl_init();
2246	curl_setopt_array($ch, array(
2247	CURLOPT_URL => "https://lindabrand.com.br/wp-json/wc/v3/orders/" . $order_id . "/?consumer_key=ck_9e747cfe973b52e14180a7c0c84aac41c8e960ec&consumer_secret=cs_225e4823dd0664b95f6030600dfebf8209ded416",
2248	CURLOPT_RETURNTRANSFER => true,
2249	CURLOPT_ENCODING => "",
2250	CURLOPT_MAXREDIRS => 10,
2251	CURLOPT_TIMEOUT => 30,
2252	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2253	CURLOPT_CUSTOMREQUEST => "GET",
2254	CURLOPT_SSL_VERIFYPEER=> false,
2255  
2256	CURLOPT_HTTPHEADER => array(
2257		"Authorization: Basic *****************",
2258		"Cache-Control: no-cache"
2259	),  
2260	));
2261	
2262	$result = curl_exec($ch);
2263	
2264	$result = curl_exec($ch);
2265
2266	$jsonResult = json_decode($result);
2267	foreach($jsonResult->meta_data as $k=>$meta){
2268		if($meta->key == "Tipo de pagamento" && $meta->value == "Boleto"){
2269			$bolVencimento = new stdClass;
2270			$bolVencimento->key = "Boleto Vencimento";
2271			$order = new WC_Order($order_id);
2272			$order_date = $order->order_date;
2273			$date = new DateTime($order_date);
2274			$date->modify("+3 day");
2275			$bolVencimento->value = $date->format("d-m-Y");
2276			$jsonResult->meta_data[] = $bolVencimento; 
2277		}
2278	}
2279
2280	$replaced_result = substr_replace(json_encode($jsonResult), '"empresa":460, "guid":"9351c4b5-8c8a-4657-8244-56cb46e5e5d8",', 12,0);
2281	
2282	//print_r($replaced_result);
2283	//echo " ";
2284	//print_r(base64_encode($replaced_result));
2285/*	$opts = [
2286	  'http' => [
2287			  'method' => 'GET'
2288	  ]
2289  ];*/
2290  
2291  //$context = stream_context_create($opts);
2292  //$result = file_get_contents('http://app.wikisistemas.com.br:8086/EcommerceExternoWebservice.asmx/RecebePedidoWooCommerce?json=' . base64_encode($replaced_result), false, $context);
2293  //var_dump($result);
2294
2295	  //
2296	  //print_r($replaced_result);
2297	  $ch2 = curl_init();
2298	curl_setopt_array($ch2, array(
2299	CURLOPT_URL => 'http://52.6.107.225/script.php?pedido=' . base64_encode($replaced_result),
2300	CURLOPT_RETURNTRANSFER => true,
2301	CURLOPT_ENCODING => "",
2302	CURLOPT_MAXREDIRS => 10,
2303	CURLOPT_TIMEOUT => 30,
2304	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2305	CURLOPT_CUSTOMREQUEST => "GET",
2306	CURLOPT_SSL_VERIFYPEER=> false,
2307  
2308	CURLOPT_HTTPHEADER => array(
2309		"Authorization: Basic *****************",
2310		"Cache-Control: no-cache"
2311	),  
2312	));
2313	
2314	$result2 = curl_exec($ch2);
2315	//echo "retorno do WS<br>";
2316	//var_dump($result2);
2317	
2318	//echo "pedido base64<br>";
2319	//var_dump($replaced_result);
2320	
2321	
2322  }
2323  
2324  
2325  add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
2326function grey_out_variations_when_out_of_stock( $grey_out, $variation ){
2327if ( ! $variation->is_in_stock() ){
2328  return false;
2329 }else{
2330  return true;
2331 }
2332}
2333