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

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


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

    // --- Menu ---
    $perfect_blogging_primary_menu_name = 'Main Menu';
    $perfect_blogging_primary_menu_location = 'primary';
    $perfect_blogging_primary_menu_exists = wp_get_nav_menu_object($perfect_blogging_primary_menu_name);

    if (!$perfect_blogging_primary_menu_exists) {
        // Create the left menu
        $perfect_blogging_primary_menu_id = wp_create_nav_menu($perfect_blogging_primary_menu_name);

        // Create and assign the Home page
        $perfect_blogging_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($perfect_blogging_home_page_id, '_wp_page_template', 'page-template/custom-front-page.php');
        update_option('page_on_front', $perfect_blogging_home_page_id);
        update_option('show_on_front', 'page');

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

        // Create and assign the Features page
        $perfect_blogging_about_us_page_id = wp_insert_post(array(
            'post_type'     => 'page',
            'post_title'    => 'Features',
            '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 Features page to the left menu
        wp_update_nav_menu_item($perfect_blogging_primary_menu_id, 0, array(
            'menu-item-title'     => __('Features', 'perfect-blogging'),
            'menu-item-classes'   => 'about-us',
            'menu-item-url'       => home_url('/about-us/'),
            'menu-item-status'    => 'publish',
            'menu-item-object-id' => $perfect_blogging_about_us_page_id,
            'menu-item-object'    => 'page',
            'menu-item-type'      => 'post_type',
        ));

        // Create and assign the Categories page
        $perfect_blogging_about_us_page_id = wp_insert_post(array(
            'post_type'     => 'page',
            'post_title'    => 'Categories',
            '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 Categories page to the left menu
        wp_update_nav_menu_item($perfect_blogging_primary_menu_id, 0, array(
            'menu-item-title'     => __('Categories', 'perfect-blogging'),
            'menu-item-classes'   => 'about-us',
            'menu-item-url'       => home_url('/about-us/'),
            'menu-item-status'    => 'publish',
            'menu-item-object-id' => $perfect_blogging_about_us_page_id,
            'menu-item-object'    => 'page',
            'menu-item-type'      => 'post_type',
        ));

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

            } else {
                    $perfect_blogging_blog_page_id = $perfect_blogging_blog_page->ID;
                }
                update_option('page_for_posts', $perfect_blogging_blog_page_id);

                wp_update_nav_menu_item($perfect_blogging_primary_menu_id, 0, array(
                    'menu-item-title'     => __('Blog', 'perfect-blogging'),
                    'menu-item-object-id' => $perfect_blogging_blog_page_id,
                    'menu-item-object'    => 'page',
                    'menu-item-type'      => 'post_type',
                    'menu-item-status'    => 'publish',    
        ));

         // Create and assign the Contact Us page
        $perfect_blogging_about_us_page_id = wp_insert_post(array(
            'post_type'     => 'page',
            'post_title'    => 'Contact Us',
            '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 Us page to the left menu
        wp_update_nav_menu_item($perfect_blogging_primary_menu_id, 0, array(
            'menu-item-title'     => __('Contact Us', 'perfect-blogging'),
            'menu-item-classes'   => 'about-us',
            'menu-item-url'       => home_url('/about-us/'),
            'menu-item-status'    => 'publish',
            'menu-item-object-id' => $perfect_blogging_about_us_page_id,
            'menu-item-object'    => 'page',
            'menu-item-type'      => 'post_type',
        ));


        // Assign left menu to its location
        $perfect_blogging_locations = get_theme_mod('nav_menu_locations', array());
        $perfect_blogging_locations[$perfect_blogging_primary_menu_location] = $perfect_blogging_primary_menu_id;
        set_theme_mod('nav_menu_locations', $perfect_blogging_locations);
    }  

     // Set the demo import completion flag
    		update_option('perfect_blogging_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.', 'perfect-blogging') . '</p>';
    		echo '<span><a href="' . esc_url(home_url()) . '" class="run-import site-btn" target="_blank">' . esc_html__('VIEW SITE', 'perfect-blogging') . '</a></span>';


    // Social Icons
    set_theme_mod( 'perfect_blog_twitter_url', '#' );
    set_theme_mod( 'perfect_blog_facebook_url', '#' );
    set_theme_mod( 'perfect_blog_skipe_url', '#' );
    set_theme_mod( 'perfect_blog_pint_url', '#' );
    set_theme_mod( 'perfect_blog_insta_url', '#' );

    // Slider
    for($perfect_blog_i=1;$perfect_blog_i<=4;$perfect_blog_i++){
       $perfect_blog_slider_title = 'LOREM IPSUM DOLOR SIT AMET';
       $perfect_blog_slider_content = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum socis natoque penatibus et magnis.';
          // Create post object
       $perfect_blog_my_post = array(
       'post_title'    => wp_strip_all_tags( $perfect_blog_slider_title ),
       'post_content'  => $perfect_blog_slider_content,
       'post_status'   => 'publish',
       'post_type'     => 'page',
       );

       // Insert the post into the database
       $perfect_blog_post_id = wp_insert_post( $perfect_blog_my_post );

       if ($perfect_blog_post_id) {
         // Set the theme mod for the slider page
         set_theme_mod('perfect_blog_slidersettings_page' . $perfect_blog_i, $perfect_blog_post_id);

          $perfect_blog_image_url = get_theme_file_uri().'/images/slider'.$perfect_blog_i.'.png';

        $perfect_blog_image_id = media_sideload_image($perfect_blog_image_url, $perfect_blog_post_id, null, 'id');

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

    // Single Category Post
    // Post Category
    set_theme_mod( 'perfect_blogging_category_post', 'category1' );

    // Define post category names and post titles
    $perfect_blog_category_names = array('category1', 'category2');
    $perfect_blog_title_array = array(
        array("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor."),
        array("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.")
    );

        foreach ($perfect_blog_category_names as $perfect_blog_index => $perfect_blog_category_name) {
            // Create or retrieve the post category term ID
            $perfect_blog_term = term_exists($perfect_blog_category_name, 'category');
            if ($perfect_blog_term === 0 || $perfect_blog_term === null) {
                // If the term does not exist, create it
                $perfect_blog_term = wp_insert_term($perfect_blog_category_name, 'category');
            }
            if (is_wp_error($perfect_blog_term)) {
                error_log('Error creating category: ' . $perfect_blog_term->get_error_message());
                continue; // Skip to the next iteration if category creation fails
            }

            for ($perfect_blog_i = 0; $perfect_blog_i < 1; $perfect_blog_i++) {
                // Create post content
                $perfect_blog_title = $perfect_blog_title_array[$perfect_blog_index][$perfect_blog_i];
                $perfect_blog_content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever.';

                // Create post post object
                $perfect_blog_my_post = array(
                    'post_title'    => wp_strip_all_tags($perfect_blog_title),
                    'post_content'  => $perfect_blog_content,
                    'post_status'   => 'publish',
                    'post_type'     => 'post', // Post type set to 'post'
                );

                // Insert the post into the database
                $perfect_blog_post_id = wp_insert_post($perfect_blog_my_post);

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

                // Assign the category to the post
                wp_set_post_categories($perfect_blog_post_id, array((int)$perfect_blog_term['term_id']));

                // Handle the featured image using media_sideload_image
                $perfect_blog_image_url =  get_theme_file_uri() . '/images/post.png';
                $perfect_blog_image_id = media_sideload_image($perfect_blog_image_url, $perfect_blog_post_id, null, 'id');

                if (is_wp_error($perfect_blog_image_id)) {
                    error_log('Error downloading image: ' . $perfect_blog_image_id->get_error_message());
                    continue; // Skip to the next post if image download fails
                }
                // Assign featured image to post
                set_post_thumbnail($perfect_blog_post_id, $perfect_blog_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.', 'perfect-blogging' ); ?></p>
        <form action="<?php echo esc_url(home_url()); ?>/wp-admin/themes.php?page=perfect_blogging_guide" method="POST" onsubmit="return validate(this);">
        <?php if (!get_option('perfect_blogging_demo_import_completed')) : ?>
            <button type="submit" name="submit" class="run-import">
                    <?php esc_html_e('Run Importer','perfect-blogging'); ?>
                    <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>
