<?php

/**
 * Wizard
 *
 * @package Whizzie
 * @author Catapult Themes
 * @since 1.0.0
 */


class Whizzie
{

	protected $version = '1.1.0';

	/** @var string Current theme name, used as namespace in actions. */
	protected $theme_name = '';
	protected $theme_title = '';

	/** @var string Wizard page slug and title. */
	protected $page_slug = '';
	protected $page_title = '';

	protected $plugin_path = '';
	protected $parent_slug = '';

	/** @var array Wizard steps set by user. */
	protected $config_steps = array();

	/**
	 * Relative plugin url for this plugin folder
	 * @since 1.0.0
	 * @var string
	 */
	protected $plugin_url = '';

	/**
	 * TGMPA instance storage
	 *
	 * @var object
	 */
	protected $tgmpa_instance;

	/**
	 * TGMPA Menu slug
	 *
	 * @var string
	 */
	protected $tgmpa_menu_slug = 'tgmpa-install-plugins';

	/**
	 * TGMPA Menu url
	 *
	 * @var string
	 */
	protected $tgmpa_url = 'themes.php?page=tgmpa-install-plugins';

	// Where to find the widget.wie file
	protected $widget_file_url = '';

	/**
	 * Constructor
	 *
	 * @param $config	Our config parameters
	 */
	public function __construct($config)
	{
		$this->set_vars($config);
		$this->init();
	}

	/**
	 * Set some settings
	 * @since 1.0.0
	 * @param $config	Our config parameters
	 */
	public function set_vars($config)
	{

		require_once trailingslashit(WHIZZIE_DIR) . 'tgmpa/required-plugins.php';
		require_once trailingslashit(WHIZZIE_DIR) . 'classes/hardware-dealer-pro-widgets.php';

		if (isset($config['page_slug'])) {
			$this->page_slug = esc_attr($config['page_slug']);
		}
		if (isset($config['page_title'])) {
			$this->page_title = esc_attr($config['page_title']);
		}
		if (isset($config['steps'])) {
			$this->config_steps = $config['steps'];
		}

		$this->plugin_path = trailingslashit(dirname(__FILE__));
		$relative_url = str_replace(get_template_directory(), '', $this->plugin_path);
		$this->plugin_url = trailingslashit(get_template_directory_uri() . $relative_url);
		$current_theme = wp_get_theme();
		$this->theme_title = $current_theme->get('Name');
		$this->theme_name = strtolower(preg_replace('#[^a-zA-Z]#', '', $current_theme->get('Name')));
		$this->page_slug = apply_filters($this->theme_name . '_theme_setup_wizard_page_slug', $this->theme_name . '-setup');
		$this->parent_slug = apply_filters($this->theme_name . '_theme_setup_wizard_parent_slug', '');

		$this->widget_file_url = trailingslashit(WHIZZIE_DIR) . 'content/hardware-dealer-pro-widgets.wie';

	}

	/**
	 * Hooks and filters
	 * @since 1.0.0
	 */
	public function init()
	{

		add_action('after_switch_theme', array($this, 'redirect_to_wizard'));
		if (class_exists('TGM_Plugin_Activation') && isset($GLOBALS['tgmpa'])) {
			add_action('init', array($this, 'get_tgmpa_instance'), 30);
			add_action('init', array($this, 'set_tgmpa_url'), 40);
		}
		add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
		add_action('admin_menu', array($this, 'menu_page'));
		add_action('admin_init', array($this, 'get_plugins'), 30);
		add_filter('tgmpa_load', array($this, 'tgmpa_load'), 10, 1);
		add_action('wp_ajax_ebp_setup_plugins', array($this, 'ebp_setup_plugins'));
		add_action('wp_ajax_hardware_dealer_pro_setup_widgets', array($this, 'hardware_dealer_pro_setup_widgets'));

		//	add_action( 'init', array( $this, 'hardware_dealer_pro_setup_widgets') );
		//	$this->hardware_dealer_pro_setup_widgets();
		//	$widgets = get_option( 'sidebars_widgets' );
		//	print_r( $widgets );

	}

	public function redirect_to_wizard()
	{
		global $pagenow;
		if (is_admin() && 'themes.php' == $pagenow && isset($_GET['activated']) && current_user_can('manage_options')) {
			wp_redirect(admin_url('themes.php?page=' . esc_attr($this->page_slug)));
		}
	}

	public function enqueue_scripts($hook)
	{
		if ($hook == 'appearance_page_' . $this->page_slug) {
			wp_enqueue_style('whizzie-style', $this->plugin_url . 'assets/css/whizzie-admin-style.css', array(), time());
			wp_register_script('whizzie', $this->plugin_url . 'assets/js/whizzie.js', array('jquery'), time());
			wp_localize_script(
				'whizzie',
				'whizzie_params',
				array(
					'ajaxurl' => admin_url('admin-ajax.php'),
					'wpnonce' => wp_create_nonce('whizzie_nonce'),
					'verify_text' => esc_html('verifying', 'whizzie')
				)
			);
			wp_enqueue_script('whizzie');
		}
	}

	public static function get_instance()
	{
		if (!self::$instance) {
			self::$instance = new self;
		}
		return self::$instance;
	}

	public function tgmpa_load($status)
	{
		return is_admin() || current_user_can('install_themes');
	}

	/**
	 * Get configured TGMPA instance
	 *
	 * @access public
	 * @since 1.1.2
	 */
	public function get_tgmpa_instance()
	{
		$this->tgmpa_instance = call_user_func(array(get_class($GLOBALS['tgmpa']), 'get_instance'));
	}

	/**
	 * Update $tgmpa_menu_slug and $tgmpa_parent_slug from TGMPA instance
	 *
	 * @access public
	 * @since 1.1.2
	 */
	public function set_tgmpa_url()
	{
		$this->tgmpa_menu_slug = (property_exists($this->tgmpa_instance, 'menu')) ? $this->tgmpa_instance->menu : $this->tgmpa_menu_slug;
		$this->tgmpa_menu_slug = apply_filters($this->theme_name . '_theme_setup_wizard_tgmpa_menu_slug', $this->tgmpa_menu_slug);
		$tgmpa_parent_slug = (property_exists($this->tgmpa_instance, 'parent_slug') && $this->tgmpa_instance->parent_slug !== 'themes.php') ? 'admin.php' : 'themes.php';
		$this->tgmpa_url = apply_filters($this->theme_name . '_theme_setup_wizard_tgmpa_url', $tgmpa_parent_slug . '?page=' . $this->tgmpa_menu_slug);
	}

	/**
	 * Make a modal screen for the wizard
	 */
	public function menu_page()
	{
		add_theme_page(esc_html__($this->page_title), esc_html__($this->page_title), 'manage_options', $this->page_slug, array($this, 'wizard_page'));
	}

	/**
	 * Make an interface for the wizard
	 */
	public function wizard_page()
	{
		tgmpa_load_bulk_installer();
		// install plugins with TGM.
		if (!class_exists('TGM_Plugin_Activation') || !isset($GLOBALS['tgmpa'])) {
			die('Failed to find TGM');
		}
		$url = wp_nonce_url(add_query_arg(array('plugins' => 'go')), 'whizzie-setup');

		// copied from TGM
		$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
		$fields = array_keys($_POST); // Extra fields to pass to WP_Filesystem.
		if (false === ($creds = request_filesystem_credentials(esc_url_raw($url), $method, false, false, $fields))) {
			return true; // Stop the normal page form from displaying, credential request form will be shown.
		}
		// Now we have some credentials, setup WP_Filesystem.
		if (!WP_Filesystem($creds)) {
			// Our credentials were no good, ask the user for them again.
			request_filesystem_credentials(esc_url_raw($url), $method, true, false, $fields);
			return true;
		}
		/* If we arrive here, we have the filesystem */ ?>
		<div class="wizard-container">
			<div class="ebp-wrap">
				<?php //printf( '<h1>%s</h1>', esc_html( $this->page_title ) );
						echo '<div class="card whizzie-wrap">';
						// The wizard is a list with only one item visible at a time
						$steps = $this->get_steps();
						echo '<ul class="whizzie-menu">';
						foreach ($steps as $step) {
							$class = 'step step-' . esc_attr($step['id']);
							echo '<li data-step="' . esc_attr($step['id']) . '" class="' . esc_attr($class) . '">';
							printf('<h2>%s</h2>', esc_html($step['title']));
							// $content is split into summary and detail
							$content = call_user_func(array($this, $step['view']));
							if (isset($content['summary'])) {
								printf(
									'<div class="summary">%s</div>',
									wp_kses_post($content['summary'])
								);
							}
							if (isset($content['detail'])) {
								// Add a link to see more detail
								printf('<p><a href="#" class="more-info">%s</a></p>', __('More Info', 'whizzie'));
								printf(
									'<div class="detail">%s</div>',
									$content['detail'] // Need to escape this
								);
							}
							// The next button
							if (isset($step['button_text']) && $step['button_text']) {
								printf(
									'<div class="wizard-button-container"><div class="button-wrap"><a href="%s" class="button button-primary do-it" data-callback="%s" data-step="%s">%s</a></div>',
									isset($step['callback_link']) ? esc_url($step['callback_link']) : '#',
									esc_attr($step['callback']),
									esc_attr($step['id']),
									esc_html($step['button_text'])
								);
							}
							// The skip button
							if (isset($step['can_skip']) && $step['can_skip']) {
								printf(
									'<div class="button-wrap" style="margin-left: 0.5em;"><a href="#" class="button button-secondary do-it" data-callback="%s" data-step="%s">%s</a></div></div>',
									'do_next_step',
									esc_attr($step['id']),
									__('Skip', 'whizzie')
								);
							}

							echo '</li>';
						}
						echo '</ul>';
						/* echo '<ul class="whizzie-nav">';
															 foreach( $steps as $step ) {
																 if( isset( $step['icon'] ) && $step['icon'] ) {
																	 echo '<li class="nav-step-' . esc_attr( $step['id'] ) . '"><span class="dashicons dashicons-' . esc_attr( $step['icon'] ) . '"></span></li>';
																 }
															 }
														 echo '</ul>'; */
						?>
				<div class="step-loading"><span class="spinner"></span></div>
			</div><!-- .whizzie-wrap -->

		</div>
		</div><!-- .ebp-wrap -->
	<?php }

	/**
	 * Set options for the steps
	 * Incorporate any options set by the theme dev
	 * Return the array for the steps
	 * @return Array
	 */
	public function get_steps()
	{
		$dev_steps = $this->config_steps;
		$steps = array(
			'intro' => array(
				'id' => 'intro',
				'title' => __('Welcome to ', 'whizzie') . $this->theme_title,
				'icon' => 'dashboard',
				'view' => 'get_step_intro', // Callback for content
				'callback' => 'do_next_step', // Callback for JS
				'button_text' => __('Start Now', 'whizzie'),
				'can_skip' => false // Show a skip button?
			),
			'plugins' => array(
				'id' => 'plugins',
				'title' => __('Plugins', 'whizzie'),
				'icon' => 'admin-plugins',
				'view' => 'get_step_plugins',
				'callback' => 'install_plugins',
				'button_text' => __('Install Plugins', 'whizzie'),
				'can_skip' => false
			),
			// 'widgets' => array(
			// 	'id'			=> 'widgets',
			// 	'title'			=> __( 'Widgets', 'whizzie' ),
			// 	'icon'			=> 'welcome-widgets-menus',
			// 	'view'			=> 'get_step_widgets',
			// 	'callback'		=> 'install_widgets',
			// 	'button_text'	=> __( 'Install Widgets', 'whizzie' ),
			// 	'can_skip'		=> true
			// ),
			'done' => array(
				'id' => 'done',
				'title' => __('Installed Required Plugins ', 'whizzie'),
				'icon' => 'yes',
				'view' => 'get_step_done',
				'callback' => 'redirect',
				'callback_link' => admin_url('admin.php?page=wpelementoimporter-wizard'),
				'button_text' => __('Start Demo Importing', 'whizzie'),
			)
		);
		unset($steps['widgets']);
		// Iterate through each step and replace with dev config values
		if ($dev_steps) {
			// Configurable elements - these are the only ones the dev can update from config.php
			$can_config = array('title', 'icon', 'button_text', 'can_skip');
			foreach ($dev_steps as $dev_step) {
				// We can only proceed if an ID exists and matches one of our IDs
				if (isset($dev_step['id'])) {
					$id = $dev_step['id'];
					if (isset($steps[$id])) {
						foreach ($can_config as $element) {
							if (isset($dev_step[$element])) {
								$steps[$id][$element] = $dev_step[$element];
							}
						}
					}
				}
			}
		}
		return $steps;
	}

	/**
	 * Print the content for the intro step
	 */
	public function get_step_intro()
	{
		$content = array();
		// The summary element will be the content visible to the user
		$content['summary'] = sprintf('<p>%s</p>', "Thank you for selecting our theme. To streamline your setup process, we've designed a quick configuration wizard. It will guide you through all the necessary steps in just a few minutes. Feel free to skip any steps you're already familiar with.", 'whizzie');
		$content['summary'] .= sprintf('<p>%s</p>', 'Click the button below to begin. If you prefer to skip the wizard for now, you can always return to this page later.', 'whizzie');
		return $content;
	}

	/**
	 * Get the content for the plugins step
	 * @return $content Array
	 */
	public function get_step_plugins()
	{
		$plugins = $this->get_plugins();
		$content = array();
		// The summary element will be the content visible to the user
		$content['summary'] = sprintf(
			'<p>%s</p>',
			__('This theme performs best with a few additional plugins. Click the button below to install them and you can always manage these plugins later from the dashboard.', 'whizzie')
		);
		$content = apply_filters('whizzie_filter_summary_content', $content);

		// The detail element is initially hidden from the user
		$content['detail'] = '<ul class="whizzie-do-plugins">';
		// Add each plugin into a list
		foreach ($plugins['all'] as $slug => $plugin) {
			$content['detail'] .= '<li data-slug="' . esc_attr($slug) . '">' . esc_html($plugin['name']) . '<span>';
			$keys = array();
			if (isset($plugins['install'][$slug])) {
				$keys[] = 'Installation';
			}
			if (isset($plugins['update'][$slug])) {
				$keys[] = 'Update';
			}
			if (isset($plugins['activate'][$slug])) {
				$keys[] = 'Activation';
			}
			$content['detail'] .= implode(' and ', $keys) . ' required';
			$content['detail'] .= '</span></li>';
		}
		$content['detail'] .= '</ul>';

		return $content;
	}

	/**
	 * Print the content for the widgets step
	 * @since 1.1.0
	 */
	public function get_step_widgets()
	{
		$content = array();
		// Check if the widgets file is included
		$file = $this->has_widget_file();
		if ($file) {
			$content['summary'] = sprintf(
				'<p>%s</p>',
				__('This theme adds content and functionality via widgets. Click the button to install these widgets - you can update them or deactivate at any time from the Customizer.', 'whizzie')
			);
		} else {
			$content['summary'] = sprintf(
				'<p>%s</p>',
				__('No widgets.wie found.', 'whizzie')
			);
		}

		$content = apply_filters('whizzie_filter_widgets_content', $content);
		return $content;
	}

	/**
	 * Print the content for the final step
	 */
	public function get_step_done()
	{
		$content = array();
		// The summary element will be the content visible to the user
		$content['summary'] = sprintf('<p>%s</p>', 'Get started with the button below for importing Elementor.', 'whizzie');
		return $content;
	}

	/**
	 * Get the plugins registered with TGMPA
	 */
	public function get_plugins()
	{
		$instance = call_user_func(array(get_class($GLOBALS['tgmpa']), 'get_instance'));
		$plugins = array(
			'all' => array(),
			'install' => array(),
			'update' => array(),
			'activate' => array()
		);
		foreach ($instance->plugins as $slug => $plugin) {
			if ($instance->is_plugin_active($slug) && false === $instance->does_plugin_have_update($slug)) {
				// Plugin is installed and up to date
				continue;
			} else {
				$plugins['all'][$slug] = $plugin;
				if (!$instance->is_plugin_installed($slug)) {
					$plugins['install'][$slug] = $plugin;
				} else {
					if (false !== $instance->does_plugin_have_update($slug)) {
						$plugins['update'][$slug] = $plugin;
					}
					if ($instance->can_plugin_activate($slug)) {
						$plugins['activate'][$slug] = $plugin;
					}
				}
			}
		}
		return $plugins;
	}

	/**
	 * Get the widgets.wie file from the /content folder
	 * @return Mixed	Either the file or false
	 * @since 1.1.0
	 */
	public function has_widget_file()
	{
		if (file_exists($this->widget_file_url)) {
			return true;
		}
		return false;
	}

	public function ebp_setup_plugins()
	{
		if (!check_ajax_referer('whizzie_nonce', 'wpnonce') || empty($_POST['slug'])) {
			wp_send_json_error(array('error' => 1, 'message' => esc_html__('No Slug Found')));
		}
		$json = array();
		// send back some json we use to hit up TGM
		$plugins = $this->get_plugins();

		// what are we doing with this plugin?
		foreach ($plugins['activate'] as $slug => $plugin) {
			if ($_POST['slug'] == $slug) {
				$json = array(
					'url' => admin_url($this->tgmpa_url),
					'plugin' => array($slug),
					'tgmpa-page' => $this->tgmpa_menu_slug,
					'plugin_status' => 'all',
					'_wpnonce' => wp_create_nonce('bulk-plugins'),
					'action' => 'tgmpa-bulk-activate',
					'action2' => -1,
					'message' => esc_html__('Activating Plugin'),
				);
				break;
			}
		}
		foreach ($plugins['update'] as $slug => $plugin) {
			if ($_POST['slug'] == $slug) {
				$json = array(
					'url' => admin_url($this->tgmpa_url),
					'plugin' => array($slug),
					'tgmpa-page' => $this->tgmpa_menu_slug,
					'plugin_status' => 'all',
					'_wpnonce' => wp_create_nonce('bulk-plugins'),
					'action' => 'tgmpa-bulk-update',
					'action2' => -1,
					'message' => esc_html__('Updating Plugin'),
				);
				break;
			}
		}
		foreach ($plugins['install'] as $slug => $plugin) {
			if ($_POST['slug'] == $slug) {
				$json = array(
					'url' => admin_url($this->tgmpa_url),
					'plugin' => array($slug),
					'tgmpa-page' => $this->tgmpa_menu_slug,
					'plugin_status' => 'all',
					'_wpnonce' => wp_create_nonce('bulk-plugins'),
					'action' => 'tgmpa-bulk-install',
					'action2' => -1,
					'message' => esc_html__('Installing Plugin'),
				);
				break;
			}
		}
		if ($json) {
			$json['hash'] = md5(serialize($json)); // used for checking if duplicates happen, move to next plugin
			wp_send_json($json);
		} else {
			wp_send_json(array('done' => 1, 'message' => esc_html__('Success')));
		}
		exit;
	}

	/**
	 * Imports the widgets.wie file
	 * @since 1.1.0
	 */


	public static function hardware_dealer_pro_setup_widgets()
	{
		ini_set('upload_max_filesize', '900M');
		ini_set('max_execution_time', '900000');
		ini_set('memory_limit', '8192M');
		$menuname = 'Primary Menu';
		$bpmenulocation = 'primary-menu';
		$menu_exists = wp_get_nav_menu_object($menuname);

		if (!$menu_exists) {
			$menu_id = wp_create_nav_menu($menuname);
			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Home', 'hardware-dealer-pro'),
					'menu-item-classes' => 'home',
					'menu-item-url' => home_url('/'),
					'menu-item-status' => 'publish'
				)
			);

			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('About Us', 'hardware-dealer-pro'),
					'menu-item-classes' => 'about-us',
					'menu-item-url' => get_permalink(get_page_by_title('About Us')),
					'menu-item-status' => 'publish'
				)
			);

			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Handyman', 'hardware-dealer-pro'),
					'menu-item-classes' => 'handyman',
					'menu-item-url' => get_permalink(get_page_by_title('Handyman')),
					'menu-item-status' => 'publish'
				)
			);

			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Shop', 'hardware-dealer-pro'),
					'menu-item-classes' => 'shop',
					'menu-item-url' => get_permalink(get_page_by_title('Shop')),
					'menu-item-status' => 'publish'
				)
			);

			$page_parent_item = wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Pages', 'hardware-dealer-pro'),
					'menu-item-classes' => 'pages',
					'menu-item-url' => get_permalink(get_page_by_title('Pages')),
					'menu-item-status' => 'publish'
				)
			);
			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Blog', 'hardware-dealer-pro'),
					'menu-item-classes' => 'blog',
					'menu-item-url' => get_permalink(get_page_by_title('Blog')),
					'menu-item-status' => 'publish',
					'menu-item-parent-id' => $page_parent_item
				)
			);
			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Team', 'hardware-dealer-pro'),
					'menu-item-classes' => 'team',
					'menu-item-url' => get_permalink(get_page_by_title('Team')),
					'menu-item-status' => 'publish',
					'menu-item-parent-id' => $page_parent_item
				)
			);
			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('FAQ', 'hardware-dealer-pro'),
					'menu-item-classes' => 'faq',
					'menu-item-url' => get_permalink(get_page_by_title('FAQ')),
					'menu-item-status' => 'publish',
					'menu-item-parent-id' => $page_parent_item
				)
			);
			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('404 Page', 'hardware-dealer-pro'),
					'menu-item-classes' => '404-page',
					'menu-item-url' => get_permalink(get_page_by_title('404 Page')),
					'menu-item-status' => 'publish',
					'menu-item-parent-id' => $page_parent_item
				)
			);


			// $parent_item = wp_update_nav_menu_item(
			// 	$menu_id,
			// 	0,
			// 	array(
			// 		'menu-item-title' => __('Blog', 'hardware-dealer-pro'),
			// 		'menu-item-classes' => 'blog',
			// 		'menu-item-url' => get_permalink(get_page_by_title('Blog')),
			// 		'menu-item-status' => 'publish'
			// 	)
			// );

			// wp_update_nav_menu_item(
			// 	$menu_id,
			// 	0,
			// 	array(
			// 		'menu-item-title' => __('Blog With No Sidebar', 'hardware-dealer-pro'),
			// 		'menu-item-classes' => 'blog-with-no-sidebar',
			// 		'menu-item-url' => get_permalink(get_page_by_title('Blog With No Sidebar')),
			// 		'menu-item-status' => 'publish',
			// 		'menu-item-parent-id' => $parent_item
			// 	)
			// );

			// wp_update_nav_menu_item(
			// 	$menu_id,
			// 	0,
			// 	array(
			// 		'menu-item-title' => __('Blog With Left Sidebar', 'hardware-dealer-pro'),
			// 		'menu-item-classes' => 'blog-with-left-sidebar',
			// 		'menu-item-url' => get_permalink(get_page_by_title('Blog With Left Sidebar')),
			// 		'menu-item-status' => 'publish',
			// 		'menu-item-parent-id' => $parent_item
			// 	)
			// );

			// wp_update_nav_menu_item(
			// 	$menu_id,
			// 	0,
			// 	array(
			// 		'menu-item-title' => __('Blog With Right Sidebar', 'hardware-dealer-pro'),
			// 		'menu-item-classes' => 'blog-with-right-sidebar',
			// 		'menu-item-url' => get_permalink(get_page_by_title('Blog With Right Sidebar')),
			// 		'menu-item-status' => 'publish',
			// 		'menu-item-parent-id' => $parent_item
			// 	)
			// );


			wp_update_nav_menu_item(
				$menu_id,
				0,
				array(
					'menu-item-title' => __('Contact Us', 'hardware-dealer-pro'),
					'menu-item-classes' => 'contact-us',
					'menu-item-url' => get_permalink(get_page_by_title('Contact Us')),
					'menu-item-status' => 'publish'
				)
			);

			if (!has_nav_menu($bpmenulocation)) {
				$locations = get_theme_mod('nav_menu_locations');
				$locations[$bpmenulocation] = $menu_id;
				set_theme_mod('nav_menu_locations', $locations);
			}
		}

	//============ Create Footer menu Start ===============
	$menuname = 'Information';
	$bpmenulocation = 'information';
	$menu_exists = wp_get_nav_menu_object($menuname);

	if (!$menu_exists) {
		$menu_id = wp_create_nav_menu($menuname);

		wp_update_nav_menu_item($menu_id, 0, array(
			'menu-item-title' => __('About Us', 'hardware-dealer-pro'),
			'menu-item-classes' => 'about-us',
			'menu-item-url' => get_permalink(get_page_by_title('About Us')),
			'menu-item-status' => 'publish'
		)
		);

		wp_update_nav_menu_item($menu_id, 0, array(
			'menu-item-title' => __('FAQ', 'hardware-dealer-pro'),
			'menu-item-classes' => 'faq',
			'menu-item-url' => get_permalink(get_page_by_title('FAQ')),
			'menu-item-status' => 'publish'
		)
		);

		wp_update_nav_menu_item($menu_id, 0, array(
			'menu-item-title' => __('Careers', 'hardware-dealer-pro'),
			'menu-item-classes' => 'careers',
			'menu-item-url' => get_permalink(get_page_by_title('Careers')),
			'menu-item-status' => 'publish'
		)
		);

		wp_update_nav_menu_item($menu_id, 0, array(
			'menu-item-title' => __('Terms & Condition', 'hardware-dealer-pro'),
			'menu-item-classes' => 'terms-condition',
			'menu-item-url' => get_permalink(get_page_by_title('Terms & Condition')),
			'menu-item-status' => 'publish'
		)
		);

		wp_update_nav_menu_item($menu_id, 0, array(
			'menu-item-title' => __('Privacy Policy', 'hardware-dealer-pro'),
			'menu-item-classes' => 'privacy-policy',
			'menu-item-url' => get_permalink(get_page_by_title('Privacy Policy')),
			'menu-item-status' => 'publish'
		)
		);


		if (!has_nav_menu($bpmenulocation)) {
			$locations = get_theme_mod('nav_menu_locations');
			$locations[$bpmenulocation] = $menu_id;
			set_theme_mod('nav_menu_locations', $locations);
		}
	}
	
	$menuname = 'Customer Care';
	$bpmenulocation = 'customer-care';
	$menu_exists = wp_get_nav_menu_object( $menuname );

		if( !$menu_exists){
			   $menu_id = wp_create_nav_menu($menuname);

			   wp_update_nav_menu_item($menu_id, 0, array(
				'menu-item-title' =>  __('My Account','hardware-dealer-pro'),
				'menu-item-classes' => 'my-account',
				'menu-item-url' => get_permalink( get_page_by_title( 'My Account' ) ),

			  //   'menu-item-url' => '#',

				'menu-item-status' => 'publish'
			));

			 wp_update_nav_menu_item($menu_id, 0, array(
				 'menu-item-title' =>  __('Track our Order','hardware-dealer-pro'),
				 'menu-item-classes' => 'track our-order',
				 'menu-item-url' => get_permalink( get_page_by_title( 'Track our Order' ) ),

			  //    'menu-item-url' => '#',
				 'menu-item-status' => 'publish'
			 ));

			 wp_update_nav_menu_item($menu_id, 0, array(
				 'menu-item-title' =>  __('Customer Services','hardware-dealer-pro'),
				 'menu-item-classes' => 'delivery-policy',
				 'menu-item-url' => get_permalink( get_page_by_title( 'Customer Services' ) ),

			  //    'menu-item-url' => '#',
				 'menu-item-status' => 'publish'
			 ));

		   wp_update_nav_menu_item($menu_id, 0, array(
				 'menu-item-title' =>  __('Return & Exchange','hardware-dealer-pro'),
				 'menu-item-classes' => 'term & condition',
				 'menu-item-url' => get_permalink( get_page_by_title( 'Return & Exchange' ) ),

			  //    'menu-item-url' => '#',
				 'menu-item-status' => 'publish'
			 ));

			 wp_update_nav_menu_item($menu_id, 0, array(
				'menu-item-title' =>  __('Payments Policy','hardware-dealer-pro'),
				'menu-item-classes' => 'term & condition',
				'menu-item-url' => get_permalink( get_page_by_title( 'Payments Policy' ) ),

			 //    'menu-item-url' => '#',
				'menu-item-status' => 'publish'
			));

			   if( !has_nav_menu( $bpmenulocation ) ){
				$locations = get_theme_mod('nav_menu_locations');
				$locations[$bpmenulocation] = $menu_id;
				set_theme_mod( 'nav_menu_locations', $locations );
			   }
	   }
	   
	   $menuname = 'Helpful Links';
	   $bpmenulocation = 'helpful-links';
	   $menu_exists = wp_get_nav_menu_object( $menuname );

		   if( !$menu_exists){
				  $menu_id = wp_create_nav_menu($menuname);

				  wp_update_nav_menu_item($menu_id, 0, array(
				   'menu-item-title' =>  __('Return Policy','hardware-dealer-pro'),
				   'menu-item-classes' => 'order & return',
				   'menu-item-url' => get_permalink( get_page_by_title( 'Return Policy' ) ),

				 //   'menu-item-url' => '#',

				   'menu-item-status' => 'publish'
			   ));

				wp_update_nav_menu_item($menu_id, 0, array(
					'menu-item-title' =>  __('Terms Of Services','hardware-dealer-pro'),
					'menu-item-classes' => 'privacy-policy',
					'menu-item-url' => get_permalink( get_page_by_title( 'Terms Of Services' ) ),

				 //    'menu-item-url' => '#',
					'menu-item-status' => 'publish'
				));

				wp_update_nav_menu_item($menu_id, 0, array(
					'menu-item-title' =>  __('Product Supports','hardware-dealer-pro'),
					'menu-item-classes' => 'delivery-policy',
					'menu-item-url' => get_permalink( get_page_by_title( 'Product Supports' ) ),

				 //    'menu-item-url' => '#',
					'menu-item-status' => 'publish'
				));


				  if( !has_nav_menu( $bpmenulocation ) ){
				   $locations = get_theme_mod('nav_menu_locations');
				   $locations[$bpmenulocation] = $menu_id;
				   set_theme_mod( 'nav_menu_locations', $locations );
				  }
		  }
		  //============ Create Footer menu End ===============

		// elemento_title_banner_image_wp_custom_attachment START
		$image_url = get_template_directory_uri() . '/assets/images/banner.png';
		$upload_dir = wp_upload_dir();
		$image_data = file_get_contents($image_url);
		$filename = basename($image_url);
		if (wp_mkdir_p($upload_dir['path'])) {
			$file = $upload_dir['path'] . '/' . $filename;
		} else {
			$file = $upload_dir['basedir'] . '/' . $filename;
		}
		file_put_contents($file, $image_data);
		$wp_filetype = wp_check_filetype($filename, null);
		$attachment = array(
			'post_mime_type' => $wp_filetype['type'],
			'post_title' => sanitize_file_name($filename),
			'post_content' => '',
			'post_status' => 'inherit'
		);
		$attach_id = wp_insert_attachment($attachment, $file);
		require_once (ABSPATH . 'wp-admin/includes/image.php');
		$attach_data = wp_generate_attachment_metadata($attach_id, $file);
		wp_update_attachment_metadata($attach_id, $attach_data);
		$attachment_url = wp_get_attachment_url($attach_id);
		// elemento_title_banner_image_wp_custom_attachment END


//==========================================================

		// Attribute Creation Code if a variable product needed to create

		$attribute_data = array(

			array(
				'name'					=>	'Size',
				'type'					=>	'button',
				'taxonomy'			=>	'pa_size',
				'data'				=>	array(
					'18mm', '20mm', '22mm','24mm'
				)
			)
		);
		$new_attribute_data = array();
		$old_attribute_taxonomies = wc_get_attribute_taxonomies();
		foreach ( $attribute_data as $attribute_data_single ) {
			$is_attribute_found	=	false;
			foreach ( $old_attribute_taxonomies as $old_attribute_taxonomy ) {
				if ( $attribute_data_single['type'] === $old_attribute_taxonomy->attribute_type ) {
					$is_attribute_found = true;
					break;
				}
			}
			if ( !$is_attribute_found ) {
				array_push( $new_attribute_data, $attribute_data_single );
			}
		}

		foreach ( $new_attribute_data as $attribute_single_args ) {
			$args = array(
				// 'slug'					=> 'my_color',
				'name'					=>	__( $attribute_single_args['name'], 'hardware-dealer-pro' ),
				'type'					=>	$attribute_single_args['type'],
				'orderby'				=>	'menu_order',
				'has_archives'	=>	false,
			);
			$wc_create_attribute	=	wc_create_attribute( $args );


			// if ( taxonomy_exists( $attribute_single_args['taxonomy'] ) ) {
			register_taxonomy( $attribute_single_args['taxonomy'], array( 'product' ), array() );
			// }

			if ( !is_wp_error( $wc_create_attribute ) ) {

				if ( ( array_keys($attribute_single_args['data']) !== range(0, count($attribute_single_args['data']) - 1) ) ) {
					foreach ( $attribute_single_args['data'] as $single_data_key => $single_data ) {
						$wp_insert_term	=	 wp_insert_term( $single_data_key, $attribute_single_args['taxonomy'] );
						if ( !is_wp_error( $wp_insert_term ) ) {
							update_term_meta( $wp_insert_term['term_id'], 'product_attribute_' . $attribute_single_args['type'], $single_data );
						}
					}
				} else {
					foreach ( $attribute_single_args['data'] as $single_data_key => $single_data ) {
						wp_insert_term( $single_data, $attribute_single_args['taxonomy'] );
					}
				}
			}
		}


// ========================================= Products Section START ===============================================					



				$_product_ids = array();

				$products_category = array(
					'Fasteners' => ['Nuts', 'Bolt', 'Screw'],
					'Adhesives and Sealants' => ['Craft Glue', 'Acrylic'],
					'Tools' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders'],
					'Painting Supplies' => ['Brushes'],
					'Hardware Accessories' => ['CPU', 'Mouse'],
					'Electrical Supplies' => ['Fuse', 'Building Wires'],
					'Garden Equipment' => ['Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork'],
					'Automotive Supplies' => ['Screw Jack', 'Hydraulic Jack'],
					'Plumbing Equipment' => ['Pliers'],
					'Hardware for out door living' => ['Chair'],
				);
			
				foreach ($products_category as $products_main_cat_name => $products_main_cat_value){
					$term = term_exists($products_main_cat_name, 'product_cat');

					if (!$term) {

					$parent_category = wp_insert_term(
					$products_main_cat_name, // the term
					'product_cat', // the taxonomy
						array(
							'description' => "Products Parent Categoty",
						)
					);
					$parent_term_id = $parent_category['term_id'];
					} 
					else {
						$parent_category = get_term_by('name', $products_main_cat_name, 'product_cat');
						$parent_term_id = $parent_category->term_id;
					}

					$image_url = get_template_directory_uri() . '/assets/images/Categories/' . str_replace(' ', '-',strtolower($products_main_cat_name)). '.png';
			// echo "<pre>";print_r($image_url);echo "<br>";exit;

			$image_name = str_replace(' ', '-',strtolower($products_main_cat_name)). '.png';
			$upload_dir = wp_upload_dir();
			// Set upload folder
			$image_data = file_get_contents($image_url);
			// Get image data
			$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
			// Generate unique name
			$filename = basename($unique_file_name);
			// Create image file name

			// Check folder permission and define file location
			if (wp_mkdir_p($upload_dir['path'])) {
				$file = $upload_dir['path'] . '/' . $filename;
			} else {
				$file = $upload_dir['basedir'] . '/' . $filename;
			}

			// Create the image  file on the server
			file_put_contents($file, $image_data);

			// Check image file type
			$wp_filetype = wp_check_filetype($filename, null);

			// Set attachment data
			$attachment = array(
				'post_mime_type' => $wp_filetype['type'],
				'post_title' => sanitize_file_name($filename),
				'post_content' => '',
				'post_type' => 'product',
				'post_status' => 'inherit'
			);

			// Create the attachment
			$attach_id = wp_insert_attachment($attachment, $file);

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

			// Define attachment metadata
			$attach_data = wp_generate_attachment_metadata($attach_id, $file);

			// Assign metadata to attachment
			wp_update_attachment_metadata($attach_id, $attach_data);

			update_term_meta($parent_category['term_id'], 'thumbnail_id', $attach_id);


// =================================   Sub Category Start  ========================

			foreach ($products_main_cat_value as $sub_cat_name){
				$subterm = term_exists($sub_cat_name, 'product_cat');
				if (!$subterm) {
				
					$sub_category = wp_insert_term(
						$sub_cat_name, // the sub term
						'product_cat', // the taxonomy
						array(
							'description' => 'This is sample sub-category',
							'parent' => $parent_term_id
						)
					);

					$sub_category_term_id = $sub_category['term_id'];
					
				} else {
					$sub_category = get_term_by('name', $sub_cat_name, 'product_cat');
					$sub_category_term_id = $sub_category->term_id;
					
				}
			}
}




$all_products = array(
	'Open Wrench' => array(
		'brand' => 'Maketa',
		'categories' => ['Craft Glue', 'Acrylic', 'Wrenches','Nuts','Screw Jack', 'Hydraulic Jack'],
	),
	'End Wrench' => array(
		'brand' => array('Dewalt'),
		'categories' => ['Craft Glue', 'Screw','Wrenches','Nuts','Screw Jack', 'Hydraulic Jack'],
	),
	'Adjustable Wrench' => array(
		'brand' => array('Bosch'),
		'categories' => ['Acrylic', 'Screw','Wrenches','Nuts','Screw Jack', 'Hydraulic Jack'],
	),
	'Chain Wrench' => array(
		'brand' => 'Maketa',
		'categories' => ['Craft Glue', 'Acrylic', 'Wrenches','Nuts','Screw Jack', 'Hydraulic Jack'],
	),
	'Armorers Wrench' => array(
		'brand' => array('Dewalt'),
		'categories' => ['Craft Glue', 'Screw','Wrenches','Nuts'],
	),
	'Dog bone wrench' => array(
		'brand' => array('Bosch'),
		'categories' => ['Acrylic', 'Screw','Wrenches','Nuts'],
	),
	'Monkey wrench' => array(
		'brand' => 'Maketa',
		'categories' => ['Craft Glue', 'Acrylic', 'Wrenches','Nuts'],
	),
	'Hex Nuts' => array(
		'brand' => array('Dewalt'),
		'categories' => ['Craft Glue', 'Screw','Wrenches','Nuts'],
	),
	'Pliers Wrench' => array(
		'brand' => array('Bosch'),
		'categories' => ['Acrylic', 'Screw','Wrenches', 'Bolt', 'Screw'],
	),
	'Anchor Bolt' => array(
		'brand' => 'Maketa',
		'categories' => ['Craft Glue', 'Acrylic', 'Wrenches', 'Bolt', 'Screw'],
	),
	'Flat Head Screw' => array(
		'brand' => array('Dewalt'),
		'categories' => ['Craft Glue', 'Screw','Wrenches', 'Bolt', 'Screw'],
	),
	'Crowfoot Wrench' => array(
		'brand' => array('Bosch'),
		'categories' => ['Acrylic', 'Screw','Wrenches', 'Bolt', 'Screw'],
	),
	'Air Jack' => array(
		'brand' => 'Maketa',
		'categories' => ['Nascent', 'Vasiaro', 'Wrenches','Brushes','Screw Jack', 'Hydraulic Jack'],
	),
	'Axle Stand Jack' => array(
		'brand' => array('Dewalt'),
		'categories' => ['Nascent', 'Shree','Wrenches','Brushes','Fuse', 'Building Wires','Screw Jack', 'Hydraulic Jack'],
	),
	'Bevel Gear Jack' => array(
		'brand' => array('Bosch'),
		'categories' => ['Vasiaro', 'Shree','Wrenches','Brushes','Fuse', 'Building Wires','Screw Jack', 'Hydraulic Jack'],
	),
	'Ball Screw Jacks' => array(
		'brand' => 'Maketa',
		'categories' => ['Nascent', 'Vasiaro', 'Wrenches','Brushes','Fuse', 'Building Wires','Screw Jack', 'Hydraulic Jack'],
	),
	'Direct Burial Wire' => array(
		'brand' => array('Dewalt'),
		'categories' => ['Nascent', 'Shree','Wrenches','Brushes','Fuse', 'Building Wires','Fuse', 'Building Wires','Pliers'],
	),
	'Ethernet' => array(
		'brand' => array('Bosch'),
		'categories' => ['Vasiaro', 'Shree','Wrenches','Brushes','Fuse', 'Building Wires','Pliers'],
	),
	'Rewireable Fuse' => array(
		'brand' => 'Ridgid',
		'categories' => ['Nascent', 'Vasiaro', 'Wrenches','Fuse', 'Building Wires','Pliers'],
	),
	'Semiconductor Fuse' => array(
		'brand' => array('Godrej'),
		'categories' => ['Nascent', 'Shree','Wrenches','Fuse', 'Building Wires','Pliers'],
	),
	'Squre Nuts' => array(
		'brand' => array('Bosch'),
		'categories' => ['Vasiaro', 'Finoflex','Wrenches','Pliers','Nuts', 'Bolt', 'Screw'],
	),
	'Steelseries Sensei Ten' => array(
		'brand' => 'Ridgid',
		'categories' => ['Nascent', 'Vasiaro', 'Wrenches','Chair','Nuts', 'Bolt', 'Screw','CPU', 'Mouse'],
	),
	'Intel Core i7-12700K' => array(
		'brand' => array('Godrej'),
		'categories' => ['Nascent', 'Finoflex','Wrenches','Pliers','Nuts', 'Bolt', 'Screw','CPU', 'Mouse'],
	),
	'Cap Nuts' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Nuts', 'Bolt', 'Screw','Pliers','Nuts', 'Bolt', 'Screw','Screwdriver'],
	),
	'Double Wheel Barrow' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Vasiaro', 'Finoflex','Wrenches','Screwdriver','Pliers','Nuts', 'Bolt', 'Screw','Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork'],
	),
	'Jam Nuts' => array(
		'brand' => array('Godrej'),
		'categories' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders','Brushes'],
	),
	'Purdy XL Serie' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders','Brushes'],
	),
	'Fan Brus' => array(
		'brand' => 'Ridgid',
		'categories' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders','Brushes'],
	),
	'Bush Hammer' => array(
		'brand' => array('Godrej'),
		'categories' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders'],
	),
	'Angle Grinder' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders'],
	),
	'Coping Saw Drill' => array(
		'brand' => 'Ridgid',
		'categories' => ['Screwdriver', 'Wrenches', 'Hammers', 'Power Tools', 'Drills', 'Saws', 'Sanders'],
	),
	'Wooster Brush' => array(
		'brand' => array('Godrej'),
		'categories' => ['Nascent', 'Shree','Brushes','Hammers','Drills','CPU', 'Mouse'],
	),
	'Brush' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Vasiaro', 'Shree','Brushes','Hammers','Drills','Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork'],
	),
	'AMD Ryzen 5 5600X' => array(
		'brand' => 'Ridgid',
		'categories' => ['CPU', 'Mouse','Power Tools','Saws','Fuse', 'Building Wires','Chair'],
	),
	'AMD Ryzen 7 5700G' => array(
		'brand' => array('Godrej'),
		'categories' => ['CPU', 'Mouse','Power Tools','Saws','Chair','Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork'],
	),
	'Ergonomic Optical Mouse' => array(
		'brand' => array('Ryobi'),
		'categories' => ['CPU', 'Mouse','Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork','Chair'],
	),
	'Garden Digging Fork' => array(
		'brand' => 'Ridgid',
		'categories' => ['Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork','CPU', 'Mouse','Chair'],
	),
	'Garden Broadfork' => array(
		'brand' => array('Godrej'),
		'categories' => ['Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork','CPU', 'Mouse','Chair'],
	),
	'Modern bentwood chair' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Vasiaro', 'Finoflex','Chair','Sanders','Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork'],
	),
	'Baby Chair' => array(
		'brand' => array('Ryobi'),
		'categories' => ['Vasiaro', 'Finoflex','Chair','Sanders','Shovels', 'Rakes', 'Wheelbarrow', 'Garden Fork'],
	),
);

$product_images = array();
foreach ($all_products as $sub_cat_plans_key => $sub_cat_plans_name) {
		
	$content = "<!-- wp:paragraph -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa officia deserunt mollit anim id est laborum. qui</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<h4>Feature of lorem ipsum dummy:-</h4>
<ul>
<li class='terms-conditions-para'>Lorem Ipsum is simply dummy text of the printing</li>
<li class='terms-conditions-para'>Lorem Ipsum is simply dummy text of the printing</li>
<li class='terms-conditions-para'>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been</li>
<li class='terms-conditions-para'>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</li>
<li class='terms-conditions-para'>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been</li>
</ul>
<!-- /wp:paragraph -->";
	$excerpt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.";
	// Create post object
	$my_post = array(
		'post_title' => wp_strip_all_tags($sub_cat_plans_key),
		'post_content' => $content,
		'post_status' => 'publish',
		'post_type' => 'product',
		'post_excerpt'  => $excerpt,
	);
	// Insert the post into the database
	$vwpost_id = wp_insert_post($my_post);

	//------------------- assign sub category start ---------------------

	// Define the subcategories to assign
    $subcategory_names = $sub_cat_plans_name['categories'];
    
    // Check if each subcategory exists and collect the valid ones
    $valid_subcategories = array();
    foreach ($subcategory_names as $subcategory_name) {
        $term = term_exists($subcategory_name, 'product_cat');
        if ($term !== 0 && $term !== null) {
            $valid_subcategories[] = $subcategory_name;
        } else {
            echo "Subcategory '$subcategory_name' does not exist.<br>";
        }
    }

    // Assign the valid subcategories to the product
    if (!empty($valid_subcategories)) {
        wp_set_object_terms($vwpost_id, $valid_subcategories, 'product_cat', true);
        echo "Product assigned to subcategories: " . implode(", ", $valid_subcategories) . ".<br>";
    } else {
        echo "No valid subcategories to assign.<br>";
    }

//------------------- assign sub category end ---------------------

	// wp_set_object_terms($vwpost_id, $sub_category_term_id, 'product_cat', true);
	wp_set_object_terms($vwpost_id, $sub_cat_plans_name['brand'], 'brand', true);
	update_post_meta($vwpost_id, 'text_after_price', "This Price Includes Taxes Applied To This Product");
	update_post_meta($vwpost_id, 'text_after_quntity', "*Certain Products Have Limited Quantities Per Customer. Please Read Additional Information About Product To Know More.");
	update_post_meta($vwpost_id, 'size_guide', get_template_directory_uri() . '/assets/images/size-guide/size-guide.png');
	// TOP SELLING START
	$var_product_top_selling_arr = array(559, 675, 785, 859, 988,199, 259, 330, 420, 524, 699, 759,884,954,154,263,368,465,527,623,786,844,948,175,296,384,436,522,675,741,855,936,163,225,341,448,565,647,795,829,941,);
	$the_top_selling = $var_product_top_selling_arr[array_rand($var_product_top_selling_arr)];
	update_post_meta($vwpost_id, 'total_sales', $the_top_selling);
	// TOP SELLING END

	// -------------- rating START -------------------------
	$author_name = array('Almas Curtis', 'John Cena', 'The Rock');
	$review_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor Incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet.';
	for ($c = 0; $c <= 2; $c++) {
		$comment_id = wp_insert_comment(
			array(
				'comment_post_ID' => $vwpost_id,
				'comment_author' => get_the_author_meta($author_name[$c - 1]),
				'comment_author_email' => get_the_author_meta('user_email'),
				'comment_content' => $review_text,
				'comment_parent' => 0,
				'user_id' => get_current_user_id(), // <== Important
				'comment_date' => date('Y-m-d H:i:s'),
				'comment_approved' => 1,
			)
		);
		update_comment_meta($comment_id, 'rating', 4);
	}
	update_post_meta($vwpost_id, 'product-rating', '5');
	array_push($_product_ids, $vwpost_id);
	update_post_meta($vwpost_id, '_stock', '10');


	//offer products START
	// if ($n == 8 || $n == 2 || $n == 5) {
	// 	update_post_meta($vwpost_id, '_sale_price_dates_from', time());
	// 	update_post_meta($vwpost_id, '_sale_price_dates_to', strtotime("11 December 2024"));
	// 	update_post_meta($vwpost_id, '_manage_stock', 'yes');
	// 	update_post_meta($vwpost_id, '_stock', '40');
	// 	update_post_meta($vwpost_id, 'total_sales', '14');
	// }



	// Now replace meta w/ new updated value array
	$image_url = get_template_directory_uri() . '/assets/images/product-images/' . str_replace(' ', '-',strtolower($sub_cat_plans_key)) . '.png';

	$image_name = $sub_cat_plans_name . '.png';
	$upload_dir = wp_upload_dir();
	// Set upload folder
	$image_data = file_get_contents(esc_url($image_url));

	// Get image data
	$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
	// Generate unique name
	$filename = basename($unique_file_name);
	// Create image file name

	// Check folder permission and define file location
	if (wp_mkdir_p($upload_dir['path'])) {
		$file = $upload_dir['path'] . '/' . $filename;
	} else {
		$file = $upload_dir['basedir'] . '/' . $filename;
	}
	// Create the image  file on the server
	file_put_contents($file, $image_data);

	// Check image file type
	$wp_filetype = wp_check_filetype($filename, null);

	// Set attachment data
	$attachment = array(
		'post_mime_type' => $wp_filetype['type'],
		'post_title' => sanitize_file_name($filename),
		'post_type' => 'product',
		'post_status' => 'inherit',
	);

	// Create the attachment
	$attach_id = wp_insert_attachment($attachment, $file, $vwpost_id);
	array_push($product_images, $attach_id);
	// Include image.php
	require_once (ABSPATH . 'wp-admin/includes/image.php');

	// Define attachment metadata
	$attach_data = wp_generate_attachment_metadata($attach_id, $file);

	// Assign metadata to attachment
	wp_update_attachment_metadata($attach_id, $attach_data);

	// update_term_meta ( $subcat_array->term_id, 'category-image-id', $attach_id );


	// And finally assign featured image to post
	set_post_thumbnail($vwpost_id, $attach_id);


	//----------- create variation product start -------------
	
	if (class_exists('WC_Meta_Box_Product_Data') && class_exists('WC_Product_Factory')) {

		// Attribute Creation in new pattern
		$attribute_taxonomies = wc_get_attribute_taxonomies();

		$attributes_data_to_insert = array();
		$index = 0;
		foreach ($attribute_taxonomies as $key => $attribute_taxonomy) {

			$taxonomy_name = 'pa_' . $attribute_taxonomy->attribute_name;
			$terms_by_taxonomy_name = get_terms(
				array(
					'taxonomy' => $taxonomy_name,
					'hide_empty' => false
				)
			);

			if (empty($terms_by_taxonomy_name)) {
				continue;
			}


			// if ( $taxonomy_name == $attr_name ) {
			$attributes_data_to_insert['attribute_names'][] = $taxonomy_name;
			$attributes_data_to_insert['attribute_position'][] = $index;
			foreach ($terms_by_taxonomy_name as $term_by_taxonomy_name) {
				$attributes_data_to_insert['attribute_values'][$index][] = $term_by_taxonomy_name->term_id;
			}
			$attributes_data_to_insert['attribute_visibility'][] = 1;
			$attributes_data_to_insert['attribute_variation'][] = 1;
			++$index;
			// }

		}

		$attributes = WC_Meta_Box_Product_Data::prepare_attributes($attributes_data_to_insert);
		$product_id = $vwpost_id;
		$product_type = 'variable';
		$classname = WC_Product_Factory::get_product_classname($product_id, $product_type);
		$product = new $classname($product_id);
		$product->set_attributes($attributes);
		$product->save();
		// Attribute Creation in new pattern ends here

		// new product variation creation code.
		$product = wc_get_product($product_id);
		$data_store = $product->get_data_store();
		$data_store->create_all_product_variations($product, 50);
		$data_store->sort_all_product_variations($product->get_id());

		$product = wc_get_product($product_id);

		update_post_meta($product_id, '_default_attributes', array("pa_more-colors" => 'brown', "pa_size" => 'l'));

		$var_product_price_arr = array(59, 75, 85, 59, 88,99, 59, 30, 20, 24, 99, 59,84,54,54,63,68,65,27,23,86,44,48,75,96,84,36,22,75,41,55,36,63,25,41,48,65,47,95,29,41,);

		

		foreach ($product->get_children() as $variation_id) {
			
			$the_price = $var_product_price_arr[array_rand($var_product_price_arr)];
			// 1. Updating the stock quantity
			update_post_meta($variation_id, '_stock', 100);
			// 2. Updating the stock quantity
			update_post_meta($variation_id, '_stock_status', wc_clean('instock'));
			update_post_meta($variation_id, '_thumbnail_id', $product_images[array_rand($product_images, 1)]);
			// 3. Updating post term relationship
			wp_set_post_terms($variation_id, 'instock', 'product_visibility', true);
			// And finally (optionally if needed)

			// Updating active price and regular price
			// update_post_meta( $variation_id, '_price', "69.00" );
			// update_post_meta( $variation_id, '_sale_price', '180' );
			// update_post_meta( $variation_id, '_regular_price', "69.00" );
			//



			update_post_meta($variation_id, '_price', $the_price);
			update_post_meta($variation_id, '_regular_price', $the_price);


			wc_delete_product_transients($variation_id); // Clear/refresh the variation cache

		}
		$swatches_arr = array(
			'default_to_button' => '',
			'default_to_image' => '',
			'default_image_type_attribute' => '',
			'pa_more-colors' => array(
				'default_type' => 'select',
				'type' => 'image',
				'style' => 'squared',
				'terms' => array(),
			),
		);
		$variation_colors = array('brown', 'red', 'white');
		for ($v = 0; $v <= 3; $v++) {
			// Now replace meta w/ new updated value array
			$image_url = get_template_directory_uri() . '/assets/images/swatches-images/img' . $v . '.png';

			$image_name = 'img' . $v . '.png';
			$upload_dir = wp_upload_dir();
			// Set upload folder
			$image_data = file_get_contents(esc_url($image_url));

			// Get image data
			$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
			// Generate unique name
			$filename = basename($unique_file_name);
			// Create image file name

			// Check folder permission and define file location
			if (wp_mkdir_p($upload_dir['path'])) {
				$file = $upload_dir['path'] . '/' . $filename;
			} else {
				$file = $upload_dir['basedir'] . '/' . $filename;
			}
			// Create the image  file on the server
			file_put_contents($file, $image_data);

			// Check image file type
			$wp_filetype = wp_check_filetype($filename, null);

			// Set attachment data
			$attachment = array(
				'post_mime_type' => $wp_filetype['type'],
				'post_title' => sanitize_file_name($filename),
				'post_type' => 'product',
				'post_status' => 'inherit',
			);

			// Create the attachment
			$attach_id = wp_insert_attachment($attachment, $file, $vwpost_id);
			$swatches_term_id = get_term_by('slug', $variation_colors[$v], 'pa_more-colors');

			$term_id = $swatches_term_id->term_id;
			$swatches_arr['pa_more-colors']['terms'][$term_id] = array(
				'type' => 'image',
				'primary_color' => '',
				'is_duel_color' => '',
				'secondary_color' => '',
				'image_id' => $attach_id,
				'show_tooltip' => '',
				'tooltip_text' => $variation_colors[$v],
				'tooltip_image_id' => '',
			);
		}


		update_post_meta($product_id, '_vw_variation_swatches_product_settings', $swatches_arr);
		// Clear/refresh the variable product cache
		wc_delete_product_transients($product_id);
		// Update the prices for all the variations ends here
	}
	// create variation product end
	// $variation_swatches = array(
	//     "default_to_button" => '',
	//     "default_to_image" => '',
	//     "default_image_type_attribute" => 'pa_more-colors',
	//     "size" => array()
	// );
	$n++;
	$l++;
}

				
		
		
// ========================================= Products Section End ===============================================

		// ======================== Blog Section START =========================

		wp_delete_post(1);

		$post_title = array('Drill VS saw tools different use ',' What are the benefits of hammers',' 10 Best Hardware Cutting Tools','Choosing Roofing Material for Home','Drill VS saw tools different use 2',' What are the benefits of hammers 2',' 10 Best Hardware Cutting Tools 2','Choosing Roofing Material for Home 2',);

		for ($i = 1; $i <= count($post_title); $i++) {

			$content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.';

			// Create post object
			$my_post = array(
				'post_title' => wp_strip_all_tags($post_title[$i - 1]),
				'post_content' => $content,
				'post_status' => 'publish',
				'post_type' => 'post',
			);
			// Insert the post into the database
			$etspost_id = wp_insert_post($my_post);

			// Insert Meta Field For Single Blog Page Start
			update_post_meta($etspost_id, 'meta_blog_title', 'Why do we use it?');
			update_post_meta($etspost_id, 'meta_blog_para_1', "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.");

			update_post_meta($etspost_id, 'meta_blog_para_2', "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.");

			update_post_meta($etspost_id, 'meta-image1', get_template_directory_uri() . '/assets/images/Single-Blog/image1.png');
			update_post_meta($etspost_id, 'meta-image2', get_template_directory_uri() . '/assets/images/Single-Blog/image2.png');

			// Insert Meta Field For Single Blog Page End
			$image_url = get_template_directory_uri() . '/assets/images/Blog/blog' . $i . '.png';

			$image_name = 'blog' . $i . '.png';
			$upload_dir = wp_upload_dir();
			// Set upload folder
			$image_data = file_get_contents($image_url);
			// Get image data
			$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
			// Generate unique name
			$filename = basename($unique_file_name);
			// Create image file name
			// Check folder permission and define file location
			if (wp_mkdir_p($upload_dir['path'])) {
				$file = $upload_dir['path'] . '/' . $filename;
			} else {
				$file = $upload_dir['basedir'] . '/' . $filename;
			}
			// Create the image  file on the server
			file_put_contents($file, $image_data);
			// Check image file type
			$wp_filetype = wp_check_filetype($filename, null);
			// Set attachment data
			$attachment = array(
				'post_mime_type' => $wp_filetype['type'],
				'post_title' => sanitize_file_name($filename),
				'post_content' => '',
				'post_type' => 'post',
				'post_status' => 'inherit'
			);
			// Create the attachment
			$attach_id = wp_insert_attachment($attachment, $file, $etspost_id);
			// Include image.php
			require_once (ABSPATH . 'wp-admin/includes/image.php');
			// Define attachment metadata
			$attach_data = wp_generate_attachment_metadata($attach_id, $file);
			// Assign metadata to attachment
			wp_update_attachment_metadata($attach_id, $attach_data);
			// And finally assign featured image to post
			set_post_thumbnail($etspost_id, $attach_id);
		}

		// ======================== Blog Section END ===========================



		// ======================== Get In Touch Section START =================
		$contact_form_title = array('Registered As A Handyman', 'Member Joining Form', 'Contact Page Form', 'Handyman Single Page Form');
		$contact_form_content = array(
'<div class="registered-form-wrapper form-group">
	<div class="form-title">
 <h4>Registered As A Handyman</h4>
 <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
<div class="form-group">
    <div class="input-with-icon">
       <i class="fa-solid fa-user"></i>
        [text* rh-your-name class:form-control placeholder "Your Name"]
    </div>
	<div class="input-with-icon">
       <i class="fa-solid fa-user"></i>
        [text* rh-last-name class:form-control placeholder "last name"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-phone"></i>
        [text* rh-phone-number class:form-control placeholder "Phone Number"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-envelope"></i>
        [email* rh-email class:form-control placeholder "Email"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-location-dot"></i>
        [text* rh-address-1 class:form-control placeholder "Address 1"]
    </div>
	 <div class="input-with-icon">
        <i class="fa-solid fa-location-dot"></i>
        [text* rh-address-2 class:form-control placeholder "Address 2"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-city"></i>
        [text* rh-city class:form-control placeholder "City"]
    </div>
	 <div class="input-with-icon">
        <i class="fa-solid fa-map"></i>
        [text* rh-state class:form-control placeholder "State"]
    </div>
	<div class="input-with-icon w-100">
        <i class="fa-solid fa-file-zipper"></i>
        [text* rh-zip-code class:form-control placeholder "Zip code"]
    </div>
	
</div>
<div class="area-experties-wrapper">
	<div class="form-title">
 		<h4>Area Of Experties</h4>
	</div>
	<div class="table-responsive-sm">
 <table class="table table-bordered">
 <thead>

	<tr>
    <th scope="col"></th>
    <th scope="col">Beginner</th>
    <th scope="col">Skilled</th>
    <th scope="col">Expert</th>
  </tr>
  </thead>
   <tbody>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> General Repairs</th>
    <td class="radio-container">[radio radio-1 "option-1-1"]</td>
    <td class="radio-container">[radio radio-1 "option-1-2"]</td>
    <td class="radio-container">[radio radio-1 "option-1-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Carpentry</th>
    <td class="radio-container">[radio radio-2 "option-2-1"]</td>
    <td class="radio-container">[radio radio-2 "option-2-2"]</td>
    <td class="radio-container">[radio radio-2 "option-2-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Plumbing</th>
    <td class="radio-container">[radio radio-3 "option-3-1"]</td>
    <td class="radio-container">[radio radio-3 "option-3-2"]</td>
    <td class="radio-container">[radio radio-3 "option-3-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Electrical Work</th>
    <td class="radio-container">[radio radio-4 "option-4-1"]</td>
    <td class="radio-container">[radio radio-4 "option-4-2"]</td>
    <td class="radio-container">[radio radio-4 "option-4-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Painting</th>
    <td class="radio-container">[radio radio-5 "option-5-1"]</td>
    <td class="radio-container">[radio radio-5 "option-5-2"]</td>
    <td class="radio-container">[radio radio-5 "option-5-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Landscaping</th>
   <td class="radio-container">[radio radio-6 "option-6-1"]</td>
    <td class="radio-container">[radio radio-6 "option-6-2"]</td>
    <td class="radio-container">[radio radio-6 "option-6-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Home Improvement</th>
    <td class="radio-container">[radio radio-7 "option-7-1"]</td>
    <td class="radio-container">[radio radio-7 "option-7-2"]</td>
    <td class="radio-container">[radio radio-7 "option-7-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Appliance Repair</th>
     <td class="radio-container">[radio radio-8 "option-8-1"]</td>
    <td class="radio-container">[radio radio-8 "option-8-2"]</td>
    <td class="radio-container">[radio radio-8 "option-8-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Flooring Services</th>
    <td class="radio-container">[radio radio-9 "option-9-1"]</td>
    <td class="radio-container">[radio radio-9 "option-9-2"]</td>
    <td class="radio-container">[radio radio-9 "option-9-3"]</td>
  </tr>
  <tr>
    <th scope="row"><i class="fa-solid fa-screwdriver-wrench"></i> Handyman Consultation</th>
    <td class="radio-container">[radio radio-10 "option-10-1"]</td>
    <td class="radio-container">[radio radio-10 "option-10-2"]</td>
    <td class="radio-container">[radio radio-10 "option-10-3"]</td>
  </tr>
   </tbody>
 </table>
</div>
</div>

<div class="input-with-icon">
        <i class="fa-solid fa-envelope"></i>
		[textarea* rh-message class:form-control placeholder "Message"]
</div>
<div class="input-with-icon submit-btn">
		<span class="icon"><i class="fa-solid fa-angle-right"></i></span>
		[submit class:rh-submit "Submit"]
</div>
</div>',

'<div class="form-title">
 <h4>Member Joining Form</h4>
 <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
<div class="form-group">
    <div class="input-with-icon">
       <i class="fa-solid fa-user"></i>
        [text* mjf-your-name class:form-control placeholder "Your Name"]
    </div>
	<div class="input-with-icon">
       <i class="fa-solid fa-user"></i>
        [text* mjf-last-name class:form-control placeholder "last name"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-phone"></i>
        [text* mjf-phone-number class:form-control placeholder "Phone Number"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-envelope"></i>
        [email* mjf-email class:form-control placeholder "Email"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-location-dot"></i>
        [text* mjf-address-1 class:form-control placeholder "Address 1"]
    </div>
	 <div class="input-with-icon">
        <i class="fa-solid fa-location-dot"></i>
        [text* mjf-address-2 class:form-control placeholder "Address 2"]
    </div>
	<div class="input-with-icon">
        <i class="fa-solid fa-city"></i>
        [text* mjf-city class:form-control placeholder "City"]
    </div>
	 <div class="input-with-icon">
        <i class="fa-solid fa-map"></i>
        [text* mjf-state class:form-control placeholder "State"]
    </div>
	<div class="input-with-icon w-100">
        <i class="fa-solid fa-file-zipper"></i>
        [text* mjf-zip-code class:form-control placeholder "Zip code"]
    </div>
	 <div class="input-with-icon textarea-wrapper w-100">
        <i class="fa-solid fa-envelope"></i>
		[textarea* mjf-message class:form-control placeholder "Message"]
    </div>
	<div class="input-with-icon submit-btn w-100">
        <span class="icon"><i class="fa-solid fa-angle-right"></i></span>
		[submit class:mjf-submit "Submit"]
    </div>
</div>',

			'<label>Name</label>
				 [text* text-257 placeholder "Enter Your Name"]
				 <label> E-mail  </label>
				 [email* email-315 placeholder "Enter Your E-mail"]
				 <label>Phone No.</label>
				 [tel* tel-411 placeholder "Enter Your Number"]
				 <label>Message</label>
				 [textarea* textarea-589 placeholder "Enter Your Message"]
				 <div class="submit_btn_icon submit-btn">
					<i class="fa-solid fa-angle-right"></i>
					[submit class:submit "Submit Now"]
				 </div>',
'<label>Name</label>
				 [text* hsp-your-name placeholder "Enter Your Name"]
				 <label> E-mail  </label>
				 [email* hsp-email placeholder "Enter Your E-mail"]
				 <label>Phone No.</label>
				 [tel* hsp-tel-411 placeholder "Enter Your Number"]
				 <label>Services</label>
				 [select* select-service class:select-field "General Repairs" "Carpentry" "Plumbing" "Electrical Work" "Painting" "Landscaping" "Home Improvement" "Appliance Repair" "Flooring Services" "Handyman Consultation"]
				 <label>Message</label>
				 [textarea* hsp-textarea-589 placeholder "Enter Your Message"]
				 <div class="submit_btn_icon submit-btn"><i class="fa-solid fa-angle-right"></i>[submit class:submit "Submit Now"]
				</div>',
		);

		for ($i = 0; $i < count($contact_form_title); $i++) {

			$cf7title1 = $contact_form_title[$i];
			$cf7content1 = $contact_form_content[$i] . '
				[_site_title] "[your-subject]"
				[_site_title] <support@wpelemento.com>
				From: [your-name] <[your-email]>
				Subject: [your-subject]

				Message Body:
				[your-message]

				--
				This e-mail was sent from a contact form on [_site_title] ([_site_url])
				[_site_admin_email]
				Reply-To: [your-email]

				0
				0

				[_site_title] "[your-subject]"
				[_site_title] <support@wpelemento.com>
				Message Body:
				[your-message]

				--
				This e-mail was sent from a contact form on [_site_title] ([_site_url])
				[your-email]
				Reply-To: [_site_admin_email]

				0
				0
				Thank you for your message. It has been sent.
				There was an error trying to send your message. Please try again later.
				One or more fields have an error. Please check and try again.
				There was an error trying to send your message. Please try again later.
				You must accept the terms and conditions before sending your message.
				The field is required.
				The field is too long.
				The field is too short.
				There was an unknown error uploading the file.
				You are not allowed to upload files of this type.
				The file is too big.
				There was an error uploading the file.';

			$cf7_post1 = array(
				'post_title' => wp_strip_all_tags($cf7title1),
				'post_content' => $cf7content1,
				'post_status' => 'publish',
				'post_type' => 'wpcf7_contact_form',
			);
			// Insert the post into the database
			$cf7post_id1 = wp_insert_post($cf7_post1);

			add_post_meta($cf7post_id1, "_form", $contact_form_content[$i]);

			$cf7mail_data1 = array(
				'subject' => '[_site_title] "[your-subject]"',
				'sender' => '[_site_title] <support@wpelemento.com>',
				'body' => 'From: [your-name] <[your-email]>
						Subject: [your-subject]

						Message Body:
						[your-message]
				--
				This e-mail was sent from a contact form on [_site_title] ([_site_url])',
				'recipient' => '[_site_admin_email]',
				'additional_headers' => 'Reply-To: [your-email]',
				'attachments' => '',
				'use_html' => 0,
				'exclude_blank' => 0
			);

			add_post_meta($cf7post_id1, "_mail", $cf7mail_data1);
			// Gets term object from Tree in the database.

			$cf7shortcode1 = '[contact-form-7 id="' . $cf7post_id1 . '" title="' . $cf7title1 . '"]';

		}


		// Shop page banner image start
		set_theme_mod('hardware_dealer_pro_banner_bgimages', get_template_directory_uri() . '/assets/images/banner.png');
		set_theme_mod('hardware_dealer_pro_banner_bgimages_pp_bg_img', get_template_directory_uri() . '/assets/images/single-page-pricing.png');

		// Shop page banner image End

		// ======================== Get In Touch Section END ===================

		// ======================== Best Handyman Section START =================

		$handyman_array_title = array(
			array(
				'title' => 'James',
				"folder_name" => "Handyman",
				"feature_img"=> "james",
				"experience" => "8",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Michael',
				"folder_name" => "Handyman",
				"feature_img"=> "michael",
				"experience" => "9",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Robert',
				"folder_name" => "Handyman",
				"feature_img"=> "robert",
				"experience" => "7",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'David',
				"folder_name" => "Handyman",
				"feature_img"=> "david",
				"experience" => "6",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'William',
				"folder_name" => "Handyman",
				"feature_img"=> "william",
				"experience" => "5",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Richard',
				"folder_name" => "Handyman",
				"feature_img"=> "richard",
				"experience" => "4",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Joseph',
				"folder_name" => "Handyman",
				"feature_img"=> "joseph",
				"experience" => "3",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Thomas',
				"folder_name" => "Handyman",
				"feature_img"=> "thomas",
				"experience" => "1",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Christopher',
				"folder_name" => "Handyman",
				"feature_img"=> "christopher",
				"experience" => "2",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Charles',
				"folder_name" => "Handyman",
				"feature_img"=> "charles",
				"experience" => "10",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			array(
				'title' => 'Daniel',
				"folder_name" => "Handyman",
				"feature_img"=> "daniel",
				"experience" => "11",
				"designation" => "General Repairs",
				"phone" => "+123 456 781",
				"email" => "rhandyman@gmail.com",
				"location" => "625, david dikate road Adventure Land",
				"commercial_plumbing" => "80",
				"residential_carpenture" => "70",
			),
			
			);
		
			foreach ($handyman_array_title as $key => $value) {
				$key++;
				$title = $value['title'];
				$content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
		
				// Create post object
				$my_post = array(
					'post_title'    => wp_strip_all_tags( $title ),
					'post_content' => $content,
					'post_status'   => 'publish',
					'post_type'     => 'handyman',
				);
		
				$handyman_id = wp_insert_post( $my_post );
		
				// update_post_meta( $handyman_id, 'swatches_color_custom_repeater', $value['car_colors']);
				update_post_meta( $handyman_id, 'handyman_designation', $value['designation']);
				update_post_meta( $handyman_id, 'handyman_experience', $value['experience']);
				update_post_meta( $handyman_id, 'handyman_phone_heading', 'Phone:');
				update_post_meta( $handyman_id, 'handyman_email_heading', 'Email:');
				update_post_meta( $handyman_id, 'handyman_location_heading', 'Location:');
				update_post_meta( $handyman_id, 'handyman_phone', $value['phone']);
				update_post_meta( $handyman_id, 'handyman_email', $value['email']);
				update_post_meta( $handyman_id, 'handyman_location', $value['location']);
				update_post_meta( $handyman_id, 'handyman_location_link', 'https://maps.app.goo.gl/rV5Yx41xmHP5F2oYA');
				update_post_meta( $handyman_id, 'handyman_personal_skill_heading', 'Personal Skills');
				update_post_meta( $handyman_id, 'handyman_personal_skill_commercial_plumbing', $value['commercial_plumbing']);
				update_post_meta( $handyman_id, 'handyman_personal_skill_residential_carpenture', $value['residential_carpenture']);
				update_post_meta( $handyman_id, 'qualification_experience_heading', 'Qualification & Experience');
				update_post_meta( $handyman_id, 'handyman_contact_form_heading', 'Contact Us');
				$full_specification_data = array('Home Maintenance','Leakage Detection','General Plumbing','Water Heating'
		);
				update_post_meta($handyman_id, 'cepr_pricing_feature',$full_specification_data);
		
				// --------------Assign the featured image START--------------
		
		
				$image_url  = get_template_directory_uri().'/assets/images/Handyman/Team0'.$key.'.png';
				
				$image_name = 'Team0'.$key.'.png';
				$upload_dir       = wp_upload_dir();
						// Set upload folder
						$services_image_data       = file_get_contents($image_url);
						// Get image data
						$services_unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name );
						// Generate unique name
						$services_filename= basename( $services_unique_file_name );
						// Create image file name
						// Check folder permission and define file location
						if( wp_mkdir_p( $upload_dir['path'] ) ) {
						$services_file = $upload_dir['path'] . '/' . $services_filename;
						} else {
						$services_file = $upload_dir['basedir'] . '/' . $services_filename;
						}
						// Create the image  file on the server
						file_put_contents( $services_file, $services_image_data );
						// Check image file type
						$wp_filetype = wp_check_filetype( $services_filename, null );
						// Set attachment data
						$attachment = array(
						'post_mime_type' => $wp_filetype['type'],
						'post_title'     => sanitize_file_name( $services_filename ),
						'post_content'   => '',
						'post_type'     => 'services',
						'post_status'    => 'inherit'
						);
						// Create the attachment
						$services_attach_id = wp_insert_attachment( $attachment, $services_file, $handyman_id );
						// Include image.php
						require_once(ABSPATH . 'wp-admin/includes/image.php');
						// Define attachment metadata
						$services_attach_data = wp_generate_attachment_metadata( $services_attach_id, $services_file );
						// Assign metadata to attachment
						wp_update_attachment_metadata( $services_attach_id, $services_attach_data );
						// And finally assign featured image to post
						set_post_thumbnail( $handyman_id, $services_attach_id );
			}

		// ======================== Best Handyman Section START =================

//=========================== Customizer Data For Home Page Start ==========================

set_theme_mod( 'cln_elemento_pro_slider_small_heading', 'Best Handyman' );
set_theme_mod( 'cln_elemento_pro_button_text', 'Book An Handyman' );
set_theme_mod( 'cln_elemento_pro_button_link', '#' );
set_theme_mod( 'cln_elemento_pro_image',get_template_directory_uri().'/assets/images/best-handyman.png' );

//=========================== Customizer Data For Home Page End ==========================

		$whizzie = new self(array());
		$whizzie->handle_elemento_cleaning_pro_setup_widgets();

	}

	public function handle_elemento_cleaning_pro_setup_widgets()
	{

		$Elemento_Widget_Importer = new Elemento_Widget_Importer;
		$Elemento_Widget_Importer->import_widgets($this->widget_file_url);
	}

}


