<div class="theme-import">
	<?php 
    // Check if the demo import has been completed
    $organic_market_demo_import_completed = get_option('organic_market_demo_import_completed', false);

    // If the demo import is completed, display the "View Site" button
        if ($organic_market_demo_import_completed) {
        echo '<p class="notice-text">' . esc_html__('Your demo import has been completed successfully.', 'organic-market') . '</p>';
        echo '<span><a href="' . esc_url(home_url()) . '"  class= "run-import view-site" target="_blank">' . esc_html__('VIEW SITE', 'organic-market') . '</a></span>';
        }

    if (isset($_POST['submit'])) {

        // Check if woocommerce is installed and activated
        if (!is_plugin_active('woocommerce/woocommerce.php')) {
          // Install the plugin if it doesn't exist
          $organic_market_plugin_slug = 'woocommerce';
          $organic_market_plugin_file = 'woocommerce/woocommerce.php';

          // Check if plugin is installed
          $organic_market_installed_plugins = get_plugins();
          if (!isset($organic_market_installed_plugins[$organic_market_plugin_file])) {
              include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
              include_once(ABSPATH . 'wp-admin/includes/file.php');
              include_once(ABSPATH . 'wp-admin/includes/misc.php');
              include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');

              // Install the plugin
              $organic_market_upgrader = new Plugin_Upgrader();
              $organic_market_upgrader->install('https://downloads.wordpress.org/plugin/woocommerce.latest-stable.zip');
          }
          // Activate the plugin
          activate_plugin($organic_market_plugin_file);
        }

        // Check if  Currency Switcher for WooCommerce is installed and activated
        if (!is_plugin_active('currency-switcher-woocommerce/currency-switcher-woocommerce.php')) {
          // Install the plugin if it doesn't exist
          $organic_market_plugin_slug = 'currency-switcher-woocommerce';
          $organic_market_plugin_file = 'currency-switcher-woocommerce/currency-switcher-woocommerce.php';

          // Check if plugin is installed
          $organic_market_installed_plugins = get_plugins();
          if (!isset($organic_market_installed_plugins[$organic_market_plugin_file])) {
              include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
              include_once(ABSPATH . 'wp-admin/includes/file.php');
              include_once(ABSPATH . 'wp-admin/includes/misc.php');
              include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');

              // Install the plugin
              $organic_market_upgrader = new Plugin_Upgrader();
              $organic_market_upgrader->install('https://downloads.wordpress.org/plugin/currency-switcher-woocommerce.latest-stable.zip');
          }
          // Activate the plugin
          activate_plugin($organic_market_plugin_file);
        }

        // Check if  GTranslate is installed and activated
        if (!is_plugin_active('gtranslate/gtranslate.php')) {
          // Install the plugin if it doesn't exist
          $organic_market_plugin_slug = 'gtranslate';
          $organic_market_plugin_file = 'gtranslate/gtranslate.php';

          // Check if plugin is installed
          $organic_market_installed_plugins = get_plugins();
          if (!isset($organic_market_installed_plugins[$organic_market_plugin_file])) {
              include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
              include_once(ABSPATH . 'wp-admin/includes/file.php');
              include_once(ABSPATH . 'wp-admin/includes/misc.php');
              include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');

              // Install the plugin
              $organic_market_upgrader = new Plugin_Upgrader();
              $organic_market_upgrader->install('https://downloads.wordpress.org/plugin/gtranslate.latest-stable.zip');
          }
          // Activate the plugin
          activate_plugin($organic_market_plugin_file);
        }

        // --- Menu ---
        $organic_market_primary_menu_name = 'Main Menu';
        $organic_market_primary_menu_location = 'primary';
        $organic_market_primary_menu_exists = wp_get_nav_menu_object($organic_market_primary_menu_name);

        if (!$organic_market_primary_menu_exists) {
            // Create the left menu
            $organic_market_primary_menu_id = wp_create_nav_menu($organic_market_primary_menu_name);

            // Create and assign the Home page
            $organic_market_home_page_id = wp_insert_post(array(
                'post_type'     => 'page',
                'post_title'    => 'Home',
                'post_content'  => '',
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_name'     => 'home'
            ));
            // Assign template and set as front page
            add_post_meta($organic_market_home_page_id, '_wp_page_template', 'page-template/custom-front-page.php');
            update_option('page_on_front', $organic_market_home_page_id);
            update_option('show_on_front', 'page');

            // Add Home page to the left menu
            wp_update_nav_menu_item($organic_market_primary_menu_id, 0, array(
                'menu-item-title'     => __('Home', 'organic-market'),
                'menu-item-classes'   => 'home',
                'menu-item-url'       => home_url('/'),
                'menu-item-status'    => 'publish',
                'menu-item-object-id' => $organic_market_home_page_id,
                'menu-item-object'    => 'page',
                'menu-item-type'      => 'post_type',
            ));

            // Create and assign the Shop page
            $organic_market_about_us_page_id = wp_insert_post(array(
                'post_type'     => 'page',
                'post_title'    => 'Shop',
                'post_content'  => 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.',
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_name'     => 'about-us'
            ));

            // Add Shop page to the left menu
            wp_update_nav_menu_item($organic_market_primary_menu_id, 0, array(
                'menu-item-title'     => __('Shop', 'organic-market'),
                'menu-item-classes'   => 'about-us',
                'menu-item-url'       => home_url('/about-us/'),
                'menu-item-status'    => 'publish',
                'menu-item-object-id' => $organic_market_about_us_page_id,
                'menu-item-object'    => 'page',
                'menu-item-type'      => 'post_type',
            ));

            // Create and assign the Product page
            $organic_market_about_us_page_id = wp_insert_post(array(
                'post_type'     => 'page',
                'post_title'    => 'Product',
                'post_content'  => 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.',
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_name'     => 'about-us'
            ));

            // Add Product page to the left menu
            wp_update_nav_menu_item($organic_market_primary_menu_id, 0, array(
                'menu-item-title'     => __('Product', 'organic-market'),
                'menu-item-classes'   => 'about-us',
                'menu-item-url'       => home_url('/about-us/'),
                'menu-item-status'    => 'publish',
                'menu-item-object-id' => $organic_market_about_us_page_id,
                'menu-item-object'    => 'page',
                'menu-item-type'      => 'post_type',
            ));

            // CREATE BLOG PAGE 
                $organic_market_blog_page = get_page_by_path('blog');
                if (!$organic_market_blog_page) {
                $organic_market_blog_page_id = wp_insert_post(array(
                        'post_type'   => 'page',
                        'post_title'  => 'Blog',
                        'post_status' => 'publish',
                        'post_name'   => 'blog',
                    ));

                } else {
                    $organic_market_blog_page_id = $organic_market_blog_page->ID;
                }
                update_option('page_for_posts', $organic_market_blog_page_id);

               wp_update_nav_menu_item($organic_market_primary_menu_id, 0, array(
                'menu-item-title'     => __('Blog', 'organic-market'),
                'menu-item-object-id' => $organic_market_blog_page_id,
                'menu-item-object'    => 'page',
                'menu-item-type'      => 'post_type',
                'menu-item-status'    => 'publish',
            ));

            // Create and assign the Pages page
            $organic_market_about_us_page_id = wp_insert_post(array(
                'post_type'     => 'page',
                'post_title'    => 'Pages',
                'post_content'  => 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.',
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_name'     => 'about-us'
            ));

            // Add Pages page to the left menu
            wp_update_nav_menu_item($organic_market_primary_menu_id, 0, array(
                'menu-item-title'     => __('Pages', 'organic-market'),
                'menu-item-classes'   => 'about-us',
                'menu-item-url'       => home_url('/about-us/'),
                'menu-item-status'    => 'publish',
                'menu-item-object-id' => $organic_market_about_us_page_id,
                'menu-item-object'    => 'page',
                'menu-item-type'      => 'post_type',
            ));

            // Create and assign the Contact page
            $organic_market_about_us_page_id = wp_insert_post(array(
                'post_type'     => 'page',
                'post_title'    => 'Contact',
                'post_content'  => 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.',
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_name'     => 'about-us'
            ));

            // Add Contact page to the left menu
            wp_update_nav_menu_item($organic_market_primary_menu_id, 0, array(
                'menu-item-title'     => __('Contact', 'organic-market'),
                'menu-item-classes'   => 'about-us',
                'menu-item-url'       => home_url('/about-us/'),
                'menu-item-status'    => 'publish',
                'menu-item-object-id' => $organic_market_about_us_page_id,
                'menu-item-object'    => 'page',
                'menu-item-type'      => 'post_type',
            ));

            // Assign left menu to its location
            $organic_market_locations = get_theme_mod('nav_menu_locations', array());
            $organic_market_locations[$organic_market_primary_menu_location] = $organic_market_primary_menu_id;
            set_theme_mod('nav_menu_locations', $organic_market_locations);
        }        

       // Set the demo import completion flag
    		update_option('organic_market_demo_import_completed', true);
    		// Display success message and "View Site" button
    		echo '<p class="notice-text">' . esc_html__('Your demo import has been completed successfully.', 'organic-market') . '</p>';
    		echo '<span><a href="' . esc_url(home_url()) . '" class="run-import site-btn" target="_blank">' . esc_html__('VIEW SITE', 'organic-market') . '</a></span>';

    //end

        // Topbar Section
        set_theme_mod( 'organic_market_topbar_text', 'Free express international delivery + easy returns' );
        set_theme_mod( 'organic_market_purchase_btn_text', 'purchase' );    
        set_theme_mod( 'organic_market_purchase_btn_url', '#' );
        set_theme_mod( 'organic_market_phone_number', '11234567890' );

        // Social Icon
        set_theme_mod( 'organic_market_facebook_url', '#' );
        set_theme_mod( 'organic_market_twitter_url', '#' );
        set_theme_mod( 'organic_market_linkedin_url', '#' );
        set_theme_mod( 'organic_market_instagram_url', '#' );
        set_theme_mod( 'organic_market_youtube_url', '#' );

        // slider section start // 
        set_theme_mod( 'organic_market_slider_small_title', 'fresh 100% organic products' );
        
        for($organic_market_i=1;$organic_market_i<=4;$organic_market_i++){
           $organic_market_slider_title = 'high-quality organic products';
           $organic_market_slider_content = 'The readable content of a page when looking at its leyput point of using of letters, as opposed.';
              // Create post object
           $my_post = array(
           'post_title'    => wp_strip_all_tags( $organic_market_slider_title ),
           'post_content'  => $organic_market_slider_content,
           'post_status'   => 'publish',
           'post_type'     => 'page',
           );

           // Insert the post into the database
           $organic_market_post_id = wp_insert_post( $my_post );

           if ($organic_market_post_id) {
             // Set the theme mod for the slider page
             set_theme_mod('organic_market_slider_page' . $organic_market_i, $organic_market_post_id);

              $organic_market_image_url = get_template_directory_uri().'/images/slider'.$organic_market_i.'.png';

            $organic_market_image_id = media_sideload_image($organic_market_image_url, $organic_market_post_id, null, 'id');

                if (!is_wp_error($organic_market_image_id)) {
                    // Set the downloaded image as the post's featured image
                    set_post_thumbnail($organic_market_post_id, $organic_market_image_id);
                }
            }
        }

        // Products Section
        set_theme_mod( 'organic_market_title', 'Our Best Seller Products' );
        set_theme_mod( 'organic_market_section_text', 'We Connected buyers & sellers of Natural, Enviromentally Sound Products' );    
        set_theme_mod( 'organic_market_best_seller_title', 'Top Seller' );
        set_theme_mod( 'organic_market_best_seller_text', 'We Connected buyers & sellers of Natural' );
        
        // Create Posts
        $organic_market_post_title = 'Video Post';
        $organic_market_post_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';

        $organic_market_video_url = 'https://www.youtube.com/embed/9xwazD5SyVg';

        $organic_market_post_content .= "\n\n[embed]{$organic_market_video_url}[/embed]";

        $organic_market_my_post = array(
            'post_title'    => wp_strip_all_tags($organic_market_post_title),
            'post_content'  => $organic_market_post_content,
            'post_status'   => 'publish',
            'post_type'     => 'post',
        );

        // Insert the post into the database
        $organic_market_post_id = wp_insert_post($organic_market_my_post);

        // Check if the post was successfully created
        if (!is_wp_error($organic_market_post_id)) {
            // Set the theme mod for the post ID
            set_theme_mod('organic_market_setting', $organic_market_post_id);
        } else {
            // Handle the error if the post creation failed
            error_log('Post creation failed: ' . $organic_market_post_id->get_error_message());
        }

        // Create Products
        set_theme_mod( 'organic_market_product_category', 'Product Category' );

        $organic_market_category_names = array('Product Category');
        $organic_market_title_array = array(
            array("Product Image 1", "Product Image 2", "Product Image 3", "Product Image 4"),
        );

        foreach ($organic_market_category_names as $organic_market_index => $organic_market_category_name) {
            // Create or retrieve the product category term ID
            $organic_market_term = term_exists($organic_market_category_name, 'product_cat');
            if ($organic_market_term === 0 || $organic_market_term === null) {
                // If the term does not exist, create it
                $organic_market_term = wp_insert_term($organic_market_category_name, 'product_cat');
            }

            if (is_wp_error($organic_market_term)) {
                error_log('Error creating category: ' . $organic_market_term->get_error_message());
                continue; // Skip to the next iteration if category creation fails
            }

            // Loop to create 4 products for each category
            for ($organic_market_i = 0; $organic_market_i < 4; $organic_market_i++) {
                // Create product content
                $organic_market_title = $organic_market_title_array[$organic_market_index][$organic_market_i];
                $organic_market_content = '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. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s.';

                // Create product post object
                $organic_market_my_post = array(
                    'post_title'    => wp_strip_all_tags($organic_market_title),
                    'post_content'  => $organic_market_content,
                    'post_status'   => 'publish',
                    'post_type'     => 'product', // Post type set to 'product'
                );

                // Insert the product into the database
                $organic_market_post_id = wp_insert_post($organic_market_my_post);

                if (is_wp_error($organic_market_post_id)) {
                    error_log('Error creating product: ' . $organic_market_post_id->get_error_message());
                    continue; // Skip to the next product if creation fails
                }

                // Assign the category to the product
                wp_set_object_terms($organic_market_post_id, (int)$organic_market_term['term_id'], 'product_cat');

                // Set product as simple product and assign a price
                update_post_meta($organic_market_post_id, '_price', '5'); 
                update_post_meta($organic_market_post_id, '_regular_price', '10'); 
                update_post_meta($organic_market_post_id, '_sale_price', '5'); // Set regular price
                update_post_meta($organic_market_post_id, '_stock_status', 'instock'); // Set stock status to 'in stock'
                update_post_meta($organic_market_post_id, '_manage_stock', 'no'); // Not managing stock for this example
                update_post_meta($organic_market_post_id, '_product_type', 'simple'); // Set product type to 'simple'

                // Handle the featured image using media_sideload_image
                $organic_market_image_url = get_template_directory_uri() . '/images/product' . ($organic_market_i + 1) . '.png';
                $organic_market_image_id = media_sideload_image($organic_market_image_url, $organic_market_post_id, null, 'id');

                if (is_wp_error($organic_market_image_id)) {
                    error_log('Error downloading image: ' . $organic_market_image_id->get_error_message());
                    continue; // Skip to the next product if image download fails
                }

                // Assign featured image to product
                set_post_thumbnail($organic_market_post_id, $organic_market_image_id);
            }
        }          
    }
    ?>
  
	<p class="note"><?php esc_html_e( 'Please Note: If your website is live and already contains data, we recommend creating a backup first. Running this importer will replace your current settings with the custom values from the demo.', 'organic-market' ); ?></p>
        <form action="<?php echo esc_url(home_url()); ?>/wp-admin/themes.php?page=organic_market_guide" method="POST" onsubmit="return validate(this);">
        <?php if (!get_option('organic_market_demo_import_completed')) : ?>
            <button type="submit" name="submit" class="run-import">
                    <?php esc_html_e('Run Importer','organic-market'); ?>
                    <span id="spinner" style="display: none;">
                        <img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/spinner.gif" alt="Loading..." style="width:34px; height:34px; vertical-align: middle;" />
                    </span>
            </button>
        <?php endif; ?>
        </form>
        <script type="text/javascript">
            function validate(valid) {
                if(confirm("Do you really want to import the theme demo content?")){
                    document.getElementById('spinner').style.display = 'inline-block';
                }
                else {
                    return false;
                }
            }
        </script>
     
     
</div>

