<?php

/**
 * The main admin functions of this plugin.
 *
 * @link       https://wpconfiguratorbuilder.com/
 * @since      1.0.0
 *
 * @package    wcb-configurator-builder
 * @subpackage wcb-configurator-builder/admin
 */

if ( ! function_exists( 'wpcb_get_configurations' ) ) {
	/**
	 * Returns an array of registered configurators fields
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_configurations() {

		$suffix = wpcb_get_i18n_suffix();

		// if ( get_transient( 'wpcb_configurations' . $suffix ) ) {

		// 	$configurations = unserialize( get_transient( 'wpcb_configurations' . $suffix ) );

		// } else {

			$configurations = array( '' => __( '- Select configuration -', 'wcb-configurator-builder' ) );

			$args = array(
				'post_type' => 'wpcb_configuration',
				'post_status' => 'publish',
				'fields' => 'ids',
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows' => true,
				'posts_per_page' => 999999,
				'orderby' => 'date',
				'order' => 'DESC',
			);
			if ( defined( 'WPCB_STRING_TRANSLATION' ) ) {
				$args['suppress_filters'] = false; // query posts from all languages
			}

			if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
				if ( 'date_asc' == $order ) {
					$args['orderby'] = 'date';
					$args['order'] = 'ASC';
				} else if ( 'title_asc' == $order ) {
					$args['orderby'] = 'title';
					$args['order'] = 'ASC';
				} else if ( 'title_desc' == $order ) {
					$args['orderby'] = 'title';
					$args['order'] = 'DESC';
				}
			}

			$field_post_ids = get_posts( $args );

			if ( is_array( $field_post_ids ) && count( $field_post_ids ) > 0 ) {
				global $wpdb;

				$sql = "SELECT ID, post_title FROM `{$wpdb->posts}` WHERE ID in (" . implode(', ', array_fill(0, count($field_post_ids), '%d')) . ")";
				$sql .= " ORDER BY post_" . $args['orderby'] . " " . $args['order'];

				$query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $field_post_ids));
				$field_posts = $wpdb->get_results( $query, ARRAY_A );

				foreach ( $field_posts as $atts ) {
					$configurations[ esc_attr( $atts['ID'] ) ] = esc_attr( $atts['post_title'] );
				}
			}

			set_transient( 'wpcb_configurations' . $suffix, serialize( $configurations ) );
		// }

        return $configurations;
	}
}

if ( ! function_exists( 'wpcb_get_configurator_choices' ) ) {
	/**
	 * Returns an array of registered configurator choices and input fields
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_configurator_choices() {

		$suffix = wpcb_get_i18n_suffix();

		// if ( get_transient( 'wpcb_configuration_choices' . $suffix ) ) {

		// 	$choices = unserialize( get_transient( 'wpcb_configuration_choices' . $suffix ) );

		// } else {

			$choices = array( '' => __( '- Select choice -', 'wcb-configurator-builder' ) );

			$args = array(
				'post_type' => 'wpcb_choice',
				'post_status' => 'publish',
				'fields' => 'ids',
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows' => true,
				'posts_per_page' => 999999,
				'orderby' => 'date',
				'order' => 'DESC',
			);
			if ( defined( 'WPCB_STRING_TRANSLATION' ) ) {
				$args['suppress_filters'] = false; // query posts from all languages
			}
			if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
				if ( 'date_asc' == $order ) {
					$args['orderby'] = 'date';
					$args['order'] = 'ASC';
				} else if ( 'title_asc' == $order ) {
					$args['orderby'] = 'title';
					$args['order'] = 'ASC';
				} else if ( 'title_desc' == $order ) {
					$args['orderby'] = 'title';
					$args['order'] = 'DESC';
				}
			}
			$field_post_ids = get_posts( $args );

			if ( is_array( $field_post_ids ) && count( $field_post_ids ) > 0 ) {
				global $wpdb;

				$sql = "SELECT ID, post_title FROM `{$wpdb->posts}` WHERE ID in (" . implode(', ', array_fill(0, count($field_post_ids), '%d')) . ")";
				$sql .= " ORDER BY post_" . $args['orderby'] . " " . $args['order'];

				$query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $field_post_ids));
				$field_posts = $wpdb->get_results( $query, ARRAY_A );

				foreach ( $field_posts as $atts ) {
					$choices[ esc_attr( $atts['ID'] ) ] = esc_attr( $atts['post_title'] );
				}
			}

			set_transient( 'wpcb_configuration_choices' . $suffix, serialize( $choices ) );
		// }

        return $choices;
	}
}

if ( ! function_exists( 'wpcb_get_configurator_choice_options' ) ) {
	/**
	 * Returns an array of registered configurator choices and input fields
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_configurator_choice_options( $choice_id = '' ) {
		
		if ( ! $choice_id ) {
			$choice_id = 'all';
		} else {
			$field_post_ids = array( $choice_id );
		}

		$suffix = wpcb_get_i18n_suffix();

		// if ( get_transient( 'wpcb_configuration_choice_options_' . $choice_id . $suffix ) ) {
			
		// 	$choice_options = unserialize( get_transient( 'wpcb_configuration_choice_options_' . $choice_id . $suffix ) );

		// } else {

			$choice_options = array(
				'' => __( '- Select option -', 'wcb-configurator-builder' )
			);
			$options = array();

			if ( 'all' === $choice_id ) {
				$args = array(
					'post_type' => 'wpcb_choice',
					'post_status' => 'publish',
					'fields' => 'ids',
					'update_post_meta_cache' => false,
					'update_post_term_cache' => false,
					'no_found_rows' => true,
					'posts_per_page' => 999999,
					'orderby' => 'date',
					'order' => 'DESC',
				);
				if ( defined( 'WPCB_STRING_TRANSLATION' ) ) {
					$args['suppress_filters'] = false; // query posts from all languages
				}
				if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
					if ( 'date_asc' == $order ) {
						$args['orderby'] = 'date';
						$args['order'] = 'ASC';
					} else if ( 'title_asc' == $order ) {
						$args['orderby'] = 'title';
						$args['order'] = 'ASC';
					} else if ( 'title_desc' == $order ) {
						$args['orderby'] = 'title';
						$args['order'] = 'DESC';
					}
				}
				$field_post_ids = get_posts( $args );
			}
	
			if ( is_array( $field_post_ids ) && count( $field_post_ids ) > 0 ) {
				global $wpdb;

				$sql = "SELECT post_id, meta_value FROM `{$wpdb->postmeta}` WHERE meta_key = '_options' AND post_id IN (" . implode(', ', array_fill(0, count($field_post_ids), '%d')) . ")";
				$query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $field_post_ids));
				$field_options = $wpdb->get_results( $query, ARRAY_A );

				foreach ( $field_options as $field_option ) {
					$post_id = sanitize_key( $field_option['post_id'] );
					$options = unserialize( $field_option['meta_value'] );
		
					foreach ( $options as $index => $option ) {
						$label = esc_attr( $option['label'][0]['value'] );
						$key = $post_id . '-' . $index;

						if ( ! array_key_exists( $key, $choice_options ) ) {
							$choice_options[ $key ] = $label;
						}
					}
				}
			}

			set_transient( 'wpcb_configuration_choice_options_' . $choice_id . $suffix, serialize( $choice_options ) );
		// }

        return $choice_options;
	}
}

if ( ! function_exists( 'wpcb_get_configurator_inputs' ) ) {
	/**
	 * Returns an array of registered configurator choices and input fields
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_configurator_inputs() {

		$suffix = wpcb_get_i18n_suffix();

		// if ( get_transient( 'wpcb_configuration_inputs' . $suffix ) ) {

		// 	$inputs = unserialize( get_transient( 'wpcb_configuration_inputs' . $suffix ) );

		// } else {

			$inputs = array( '' => __( '- Select input -', 'wcb-configurator-builder' ) );

			$args = array(
				'post_type' => 'wpcb_input',
				'post_status' => 'publish',
				'fields' => 'ids',
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows' => true,
				'posts_per_page' => 999999,
				'orderby' => 'date',
				'order' => 'DESC',
			);
			if ( defined( 'WPCB_STRING_TRANSLATION' ) ) {
				$args['suppress_filters'] = false; // query posts from all languages
			}
			if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
				if ( 'date_asc' == $order ) {
					$args['orderby'] = 'date';
					$args['order'] = 'ASC';
				} else if ( 'title_asc' == $order ) {
					$args['orderby'] = 'title';
					$args['order'] = 'ASC';
				} else if ( 'title_desc' == $order ) {
					$args['orderby'] = 'title';
					$args['order'] = 'DESC';
				}
			}
			$field_post_ids = get_posts( $args );

			if ( is_array( $field_post_ids ) && count( $field_post_ids ) > 0 ) {
				global $wpdb;

				$sql = "SELECT ID, post_title FROM `{$wpdb->posts}` WHERE ID in (" . implode(', ', array_fill(0, count($field_post_ids), '%d')) . ")";
				$sql .= " ORDER BY post_" . $args['orderby'] . " " . $args['order'];

				$query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $field_post_ids));
				$field_posts = $wpdb->get_results( $query, ARRAY_A );

				foreach ( $field_posts as $atts ) {
					$inputs[ esc_attr( $atts['ID'] ) ] = esc_attr( $atts['post_title'] );
				}
			}

			set_transient( 'wpcb_configuration_inputs' . $suffix, serialize( $inputs ) );
		// }

        return $inputs;
	}
}

if ( ! function_exists( 'wpcb_get_configurator_fields' ) ) {
	/**
	 * Queries the database for all WCB choices and inputs.
	 *
	 * @since    1.0.0.
	 */
	function wpcb_get_configurator_fields() {
		$fields[''] = __( '- Select field -', 'wcb-configurator-builder' );

		$choices = wpcb_get_configurator_choices();
		foreach ( $choices as $choice_id => $choice_label ) {
			if ( '' === $choice_id ) { 
				continue;
			}
			$fields[ $choice_id ] = $choice_label;
		}

		$inputs = wpcb_get_configurator_inputs();
		foreach ( $inputs as $input_id => $input_label ) {
			if ( '' === $input_id ) { 
				continue;
			}
			$fields[ $input_id ] = $input_label;
		}
		
		return $fields;
	}
}

if ( ! function_exists( 'wpcb_get_visuals' ) ) {
	/**
	 * Queries the database for all WCB visuals
	 *
	 * @since    1.0.0.
	 */
	function wpcb_get_visuals() {
		$visuals = array( '' => __( '- Select visual -', 'wcb-configurator-builder' ) );

		$args = array(
			'post_type' => 'wpcb_visual',
			'post_status' => 'publish',
			'fields' => 'ids',
			'update_post_meta_cache' => false,
			'update_post_term_cache' => false,
			'no_found_rows' => true,
			'posts_per_page' => 999999,
			'orderby' => 'date',
			'order' => 'DESC',
		);
		if ( defined( 'WPCB_STRING_TRANSLATION' ) ) {
			$args['suppress_filters'] = false; // query posts from all languages
		}

		if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
			if ( 'date_asc' == $order ) {
				$args['orderby'] = 'date';
				$args['order'] = 'ASC';
			} else if ( 'title_asc' == $order ) {
				$args['orderby'] = 'title';
				$args['order'] = 'ASC';
			} else if ( 'title_desc' == $order ) {
				$args['orderby'] = 'title';
				$args['order'] = 'DESC';
			}
		}

		$field_post_ids = get_posts( $args );

		if ( is_array( $field_post_ids ) && count( $field_post_ids ) > 0 ) {
			global $wpdb;

			$sql = "SELECT ID, post_title FROM `{$wpdb->posts}` WHERE ID in (" . implode(', ', array_fill(0, count($field_post_ids), '%d')) . ")";
			$sql .= " ORDER BY post_" . $args['orderby'] . " " . $args['order'];

			$query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $field_post_ids));
			$field_posts = $wpdb->get_results( $query, ARRAY_A );

			foreach ( $field_posts as $atts ) {
				$visuals[ esc_attr( $atts['ID'] ) ] = esc_attr( $atts['post_title'] );
			}
		}

		return $visuals;
	}
}

if ( ! function_exists( 'wpcb_get_configurator_percentage_fields' ) ) {
	/**
	 * Queries the database for all WCB choices and inputs and add percentage default fields
	 *
	 * @since    1.0.0.
	 */
	function wpcb_get_configurator_percentage_fields() {
		$fields = wpcb_get_configurator_fields();

		$fields['product_price'] = __( 'Configuration product price', 'wcb-configurator-builder' );
		$fields['option_price'] = __( 'Configuration options price', 'wcb-configurator-builder' );
		$fields['total_price'] = __( 'Configuration totals price', 'wcb-configurator-builder' );

		return $fields;
	}
}

if ( ! function_exists( 'wpcb_get_product_list' ) ) {
	/**
	 * Queries the database for products that are not configurable.
	 *
	 * @since    1.0.0.
	 */
	function wpcb_get_product_list() {
		$products = array( '' => __( '- Select product -', 'wcb-configurator-builder' ) );

		// if ( function_exists( 'fluentCart' ) ) {
		// 	$args = array(
		// 		'post_type' => 'fluent-products',
		// 		'post_status' => 'any',
		// 		'posts_per_page' => 999999,
		// 		'orderby' => 'date',
		// 		'order'   => 'DESC',
		// 		'fields'   => 'ids',
		// 	);

		// 	if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
		// 		if ( 'date_asc' == $order ) {
		// 			$args['orderby'] = 'date';
		// 			$args['order'] = 'ASC';
		// 		} else if ( 'title_asc' == $order ) {
		// 			$args['orderby'] = 'name';
		// 			$args['order'] = 'ASC';
		// 		} else if ( 'title_desc' == $order ) {
		// 			$args['orderby'] = 'name';
		// 			$args['order'] = 'DESC';
		// 		}
		// 	}

		// 	if ( defined( 'ICL_LANGUAGE_CODE' ) && ! defined( 'WPCB_STRING_TRANSLATION' ) ) {
		// 		$args['lang'] = ICL_LANGUAGE_CODE;
		// 	}

		// 	$product_ids = get_posts( $args );
		// 	foreach ( $product_ids as $product_id ) {
		// 		$products[ $product_id ] = get_the_title( $product_id );
		// 	}
		// }
		
		if ( function_exists( 'wc_get_products' ) ) {
			$args = array(
				'limit'   => 999999,
				'type'    => array( 'simple', 'variable' ),
				'orderby' => 'date',
				'order'   => 'DESC',
				'return'  => 'ids',
			);
			if ( $order = wpcb_get_option( 'wpcb_post_type_order' ) ) {
				if ( 'date_asc' == $order ) {
					$args['orderby'] = 'date';
					$args['order'] = 'ASC';
				} else if ( 'title_asc' == $order ) {
					$args['orderby'] = 'name';
					$args['order'] = 'ASC';
				} else if ( 'title_desc' == $order ) {
					$args['orderby'] = 'name';
					$args['order'] = 'DESC';
				}
			}

			if ( defined( 'ICL_LANGUAGE_CODE' ) && ! defined( 'WPCB_STRING_TRANSLATION' ) ) {
				$args['lang'] = ICL_LANGUAGE_CODE;
			}

			$product_ids = wc_get_products( $args );
			foreach ( $product_ids as $product_id ) {
				$products[ $product_id ] = get_the_title( $product_id );
			}
		}

		return $products;
	}
}

if ( ! function_exists( 'wpcb_get_category_list' ) ) {
	/**
	 * Queries the database for product categories
	 *
	 * @since    1.0.0.
	 */
	function wpcb_get_category_list() {
		$product_cats = array();

		$product_terms = get_terms( array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => false,
		));
		if ( ! is_array( $product_terms ) || count( $product_terms ) == 0 ) {
			return $product_cats;
		}

		foreach ( $product_terms as $product_term ) {
			$product_cats[ $product_term->term_id ] = $product_term->name;
		}

		return $product_cats;
	}
}

if ( ! function_exists( 'wpcb_get_tag_list' ) ) {
	/**
	 * Queries the database for product tags
	 *
	 * @since    1.0.0.
	 */
	function wpcb_get_tag_list() {
		$product_tags = array();

		$product_terms = get_terms( array(
			'taxonomy'   => 'product_tag',
			'hide_empty' => false,
		));
		if ( ! is_array( $product_terms ) || count( $product_terms ) == 0 ) {
			return $product_tags;
		}

		foreach ( $product_terms as $product_term ) {
			$product_tags[ $product_term->term_id ] = $product_term->name;
		}

		return $product_tags;
	}
}

if ( ! function_exists( 'wpcb_get_roles' ) ) {
	/**
	 * Get WordPress roles
	 * 
	 * @since 1.0.0.
	 */
	function wpcb_get_roles() {
		global $wp_roles;

		$roles = array();
		foreach ( $wp_roles->roles as $role => $details ) {
			$roles[ $role ] = $details['name'];
		}

		unset( $roles['administrator'] );

    	return $roles;
	}
}

if ( ! function_exists( 'wpcb_get_woocommerce_tax_classes' ) ) {
	/**
	 * Get TablePress tables
	 * 
	 * @since 1.0.0.
	 */
	function wpcb_get_woocommerce_tax_classes() {
		$all_tax_rates = [];
		if ( ! class_exists('WC_Tax') ) {
			return $all_tax_rates;
		}
		
		$tax_classes = WC_Tax::get_tax_classes(); // Retrieve all tax classes.
		if ( ! in_array( '', $tax_classes ) ) { // Make sure "Standard rate" (empty class name) is present.
			array_unshift( $tax_classes, '' );
		}

		foreach ( $tax_classes as $tax_class ) { // For each tax class, get all rates.
			if ( '' === $tax_class ) {
				$all_tax_rates[ $tax_class ] = __( 'Standard', 'wcb-configurator-builder' );
			} else {
				$all_tax_rates[ $tax_class ] = $tax_class;
			}
		}

		return $all_tax_rates;
	}
}

if ( ! function_exists( 'wpcb_get_registered_image_sizes' ) ) {
	/**
	 * Returns an array of registered image sizes
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_registered_image_sizes() {
		global $_wp_additional_image_sizes;

        $sizes = array();
        foreach ( get_intermediate_image_sizes() as $s ) {
            $sizes[$s] = array(0, 0);
            if ( in_array( $s, array( 'thumbnail', 'medium', 'medium_large', 'large' ) ) ) {
                $sizes[$s][0] = get_option($s . '_size_w');
                $sizes[$s][1] = get_option($s . '_size_h');
            } else {
                if ( isset( $_wp_additional_image_sizes ) && isset( $_wp_additional_image_sizes[$s] ) ) {
                    $sizes[ $s ] = array( $_wp_additional_image_sizes[$s]['width'], $_wp_additional_image_sizes[$s]['height'] );
				}
            }
        }

        return $sizes;
	}
}

if ( ! function_exists( 'wpcb_get_image_size_choices' ) ) {
	/**
	 * Returns an array of registered image sizes
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_image_size_choices() {
        $image_sizes = wpcb_get_registered_image_sizes();
		$choices = array( '' => '- Select image size -');

		foreach ( $image_sizes as $size => $atts ) {
			$choices[ $size ] = $size . ' (' . implode('x', $atts) . ')';
		}

        return $choices;
	}
}

if ( ! function_exists( 'wpcb_ajax_get_configurator_image_link' ) ) {
	/**
	 * Get configuration image link URL
	 *
	 * @since    1.0.0
	 */
	function wpcb_ajax_get_configurator_image_link() {
		check_ajax_referer('wpcb-ajax-nonce', 'nonce');

		$image = sanitize_text_field( wp_unslash( $_POST['image'] ) );
		$name = wpcb_generate_configuration_name();
		$url = false;
		if ( str_contains( $image, ';base64,' ) ) {
			$url = wpcb_store_configuration_image( $name, $image, true );
		}

		echo wp_send_json_success( array(
			'url' => $url,
			'name' => $name,
		) );
		die();
	}
}
add_action( 'wp_ajax_nopriv_wpcb_get_configurator_image_link', 'wpcb_ajax_get_configurator_image_link' );
add_action( 'wp_ajax_wpcb_get_configurator_image_link', 'wpcb_ajax_get_configurator_image_link' );

if ( ! function_exists( 'wpcb_ajax_get_configurator_attribute_values' ) ) {
	/**
	 * Get choice options via AJAX call.
	 *
	 * @since    1.0.0
	 */
	function wpcb_ajax_get_configurator_attribute_values() {
		$choice_id = sanitize_key( $_POST['choice_id'] );
		$results_dictionary = wpcb_get_configurator_choice_options( $choice_id );

		echo wp_json_encode( $results_dictionary );
		die();
	}
}
add_action( 'wp_ajax_nopriv_wpcb_get_configurator_attribute_values', 'wpcb_ajax_get_configurator_attribute_values' );
add_action( 'wp_ajax_wpcb_get_configurator_attribute_values', 'wpcb_ajax_get_configurator_attribute_values' );

if ( ! function_exists( 'wpcb_serialize_blocks' ) ) {
    /**
     * Custom serialize blocks function that also supports serializing nested blocks
     * 
     */
    function wpcb_serialize_blocks($blocks) {
        $output = '';

        foreach ($blocks as $block) {
            $blockName = $block['blockName'] ?? null;
            $attrs     = $block['attrs'] ?? [];
            $inner     = $block['innerBlocks'] ?? [];

			if ( ! $blockName && ( ! is_array( $inner ) || count( $inner ) == 0 ) ) {
				continue;
			}

            // Serialize block comment start
            $output .= '<!-- wp:' . $blockName;

            if (!empty($attrs)) {
                $output .= ' ' . wp_json_encode($attrs);
            }

            $output .= ' -->';

            // Recursively add inner blocks if any
            if (!empty($inner)) {
                $output .= wpcb_serialize_blocks($inner);
            }

            // End block comment
            $output .= '<!-- /wp:' . $blockName . ' -->';
        }

        return $output;
    }
}

if ( ! function_exists( 'wpcb_get_attachment_id_by_url' ) ) {
	/**
	 * Checks if an attachment image exists by image url.
	 *
	 * @since    1.0.0
	 */
	function wpcb_get_attachment_id_by_url($image_url) {
		global $wpdb;

		$file_name   = esc_attr(basename($image_url));
		$wp_filetype = wp_check_filetype($file_name, null);
		$image_name  = str_replace( '.' . $wp_filetype['ext'], '', $file_name);

		$query    = $wpdb->prepare("SELECT `ID` FROM $wpdb->posts WHERE `post_type`='attachment' AND ( `post_name`= %s OR `guid` = %s )", $image_name, $image_url);
		$image_id = intval($wpdb->get_var($query));
		if (0 === (int) $image_id) {
			$image_id = wpcb_download_image_from_url($image_url);
		}

		return $image_id;
	}
}

if ( ! function_exists( 'wpcb_download_image_from_url' ) ) {
	/**
	 * Download image by URL and generate attachment data.
	 *
	 * @since    1.0.0
	 */
	function wpcb_download_image_from_url($imageurl) {
		global $wp_filesystem;

		include_once ABSPATH . 'wp-admin/includes/image.php';
		require_once(ABSPATH . 'wp-admin/includes/file.php');

		$filename    = basename($imageurl);
		$uploaddir  = wp_upload_dir();
		$uploadurl  = $uploaddir['url'] . '/' . $filename;
		$uploadfile  = $uploaddir['path'] . '/' . $filename;

		$data = wp_remote_get($imageurl);
		if ( ! $data || is_wp_error($data) ) {
			return false;
		}

		$contents = $data['body'];
		if ( ! $wp_filesystem ) {
			WP_Filesystem();
		}
		$wp_filesystem->put_contents($uploadfile, $contents);

		$wp_filetype   = wp_check_filetype(basename($filename), null);
		$wp_file_url   = $uploadurl;
		$wp_file_title = str_replace( '.' . $wp_filetype['ext'], '', $filename );

		$attachment = array(
			'post_mime_type' => $wp_filetype['type'],
			'post_title'     => $wp_file_title,
			'post_content'   => '',
			'post_status'    => 'inherit',
			'guid'           => $wp_file_url,
		);

		$attach_id    = wp_insert_attachment($attachment, $uploadfile);
		$imagenew     = get_post($attach_id);
		$fullsizepath = get_attached_file($imagenew->ID);
		$attach_data  = wp_generate_attachment_metadata($attach_id, $fullsizepath);

		wp_update_attachment_metadata($attach_id, $attach_data);

		return $attach_id;
	}
}
