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

        // If the demo import is completed, display the "View Site" button
        if ($ebooks_collection_demo_import_completed) {
            echo '<br>';
            echo '<div class="success">Demo Import Successful</div>';
            echo '<br>';
            echo '<hr>';
            echo '<br>';
            echo '<span>' . esc_html__( 'You can now visit your site or customize it further.', 'ebooks-collection' ) . '</span>';
            echo '<br>';
            echo '<br>';
            echo '<br>';
            echo '<div class="view-site-btn">';
            echo '<a href="' . esc_url(home_url()) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">View Site</a>';
            echo '<a href="' . esc_url( admin_url('customize.php') ) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">Customize Demo Content</a>';
            echo '</div>';
        }
    if ( isset( $_POST['submit'] ) ) {

        echo '<div class="plugin-notice">';
            // Check if Classic Blog Grid plugin is installed
            if (!is_plugin_active('classic-blog-grid/classic-blog-grid.php')) {
                // Plugin slug and file path for Classic Blog Grid
                $ebooks_collection_plugin_slug = 'classic-blog-grid';
                $ebooks_collection_plugin_file = 'classic-blog-grid/classic-blog-grid.php';
            
                // Check if Classic Blog Grid is installed and activated
                if ( ! is_plugin_active( $ebooks_collection_plugin_file ) ) {
            
                    // Check if Classic Blog Grid is installed
                    $ebooks_collection_installed_plugins = get_plugins();
                    if ( ! isset( $ebooks_collection_installed_plugins[ $ebooks_collection_plugin_file ] ) ) {
            
                        // Include necessary files to install plugins
                        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' );
            
                        // Download and install Classic Blog Grid
                        $ebooks_collection_upgrader = new Plugin_Upgrader();
                        $ebooks_collection_upgrader->install( 'https://downloads.wordpress.org/plugin/classic-blog-grid.latest-stable.zip' );
                    }
            
                    // Activate the Classic Blog Grid plugin after installation (if needed)
                    activate_plugin( $ebooks_collection_plugin_file );
                }
            }

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

                // Check if plugin is installed
                $ebooks_collection_installed_plugins = get_plugins();
                if (!isset($ebooks_collection_installed_plugins[$ebooks_collection_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
                    $ebooks_collection_upgrader = new Plugin_Upgrader();
                    $ebooks_collection_upgrader->install('https://downloads.wordpress.org/plugin/woocommerce.latest-stable.zip');
                }
                // Activate the plugin
                activate_plugin($ebooks_collection_plugin_file);
            }
        echo '</div>';

        // ------- Create Main Menu --------
        $ebooks_collection_menuname = 'Primary Menu';
        $ebooks_collection_bpmenulocation = 'primary';
        $ebooks_collection_menu_exists = wp_get_nav_menu_object( $ebooks_collection_menuname );
    
        if (!$ebooks_collection_menu_exists) {
            // Create a new menu
            $ebooks_collection_menu_id = wp_create_nav_menu($ebooks_collection_menuname);

            // Define pages to be created
            $ebooks_collection_pages = array(
                'home' => array(
                    'title' => 'Home',
                    'template' => '/templates/template-home-page.php'
                ),
                'about-us' => array(
                    'title' => 'About Us',
                    'content' => '<p>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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 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.</p>'
                ),
                'pages' => array(
                    'title' => 'Pages',
                    'content' => '<p>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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 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.</p>'
                ),
                'blogs' => array(
                    'title' => 'Blogs',
                    'content' => ''
                ),
            );

            $ebooks_collection_page_ids = array();

            // Loop through the pages and create them if they don’t exist
            foreach ($ebooks_collection_pages as $ebooks_collection_slug => $ebooks_collection_data) {
                $ebooks_collection_existing_page = get_page_by_path($ebooks_collection_slug);

                if ($ebooks_collection_existing_page) {
                    // If the page already exists, use its ID
                    $ebooks_collection_page_id = $ebooks_collection_existing_page->ID;
                } else {
                    // Create a new page
                    $ebooks_collection_page_data = array(
                        'post_type'    => 'page',
                        'post_title'   => $ebooks_collection_data['title'],
                        'post_content' => isset($ebooks_collection_data['content']) ? $ebooks_collection_data['content'] : '',
                        'post_status'  => 'publish',
                        'post_author'  => get_current_user_id(), // Set author dynamically
                        'post_name'    => $ebooks_collection_slug,
                    );

                    $ebooks_collection_page_id = wp_insert_post($ebooks_collection_page_data);

                    // Assign custom page template if specified
                    if (!empty($ebooks_collection_data['template'])) {
                        update_post_meta($ebooks_collection_page_id, '_wp_page_template', $ebooks_collection_data['template']);
                    }
                }

                // Store the page IDs
                $ebooks_collection_page_ids[$ebooks_collection_slug] = $ebooks_collection_page_id;
            }

            // Set homepage and blog page
            update_option('page_for_posts', $ebooks_collection_page_ids['blogs']);
            update_option('page_on_front', $ebooks_collection_page_ids['home']);
            update_option('show_on_front', 'page');

            // Define menu items
            $ebooks_collection_menu_items = array(
                'home',
                'about-us',
                'pages',
                'blogs',
            );

            // Add menu items dynamically
            foreach ($ebooks_collection_menu_items as $ebooks_collection_slug) {
                wp_update_nav_menu_item($ebooks_collection_menu_id, 0, array(
                    'menu-item-title' => esc_html($ebooks_collection_pages[$ebooks_collection_slug]['title']),
                    'menu-item-url' => get_permalink($ebooks_collection_page_ids[$ebooks_collection_slug]),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $ebooks_collection_page_ids[$ebooks_collection_slug],
                    'menu-item-object' => 'page',
                    'menu-item-type' => 'post_type',
                ));
            }

            // Assign menu to theme location
            $ebooks_collection_locations = get_theme_mod('nav_menu_locations', array());
            $ebooks_collection_locations[$ebooks_collection_bpmenulocation] = $ebooks_collection_menu_id;
            set_theme_mod('nav_menu_locations', $ebooks_collection_locations);
        }

        //Logo
        set_theme_mod( 'ebooks_collection_the_custom_logo', esc_url( get_template_directory_uri().'/images/Logo.png'));

        //Slider Section
        set_theme_mod( 'ebooks_collection_slider', true);
        set_theme_mod( 'ebooks_collection_button_text', 'Learn More');
        set_theme_mod( 'ebooks_collection_button_text2', 'Shop Now');
        set_theme_mod( 'ebooks_collection_button_link_slider2', '#');
        
        $ebooks_collection_slider_category_id = wp_create_category('Slider');

        // Set the category in theme mods for the slider section
        set_theme_mod('ebooks_collection_slider_cat', 'Slider'); // Update with correct category ID
        
        // Titles for the three posts
        $ebooks_collection_titles = array(
            'YOUR FAVOURITE EBOOK',
            'TOP 10 MUST-READ EBOOKS',
            'EXPLORE OUR DIGITAL LIBRARY'
        );               
        // Create three demo posts and assign them to the 'Slider' category
        for ($ebooks_collection_i = 1; $ebooks_collection_i <= 3; $ebooks_collection_i++) {
            $ebooks_collection_title = $ebooks_collection_titles[$ebooks_collection_i - 1];
            $ebooks_collection_content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry.';
        
            // Prepare the post object
            $ebooks_collection_my_post = array(
                'post_title'    => wp_strip_all_tags($ebooks_collection_title),
                'post_content'  => $ebooks_collection_content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => array($ebooks_collection_slider_category_id),
            );
        
            // Insert the post into the database
            $ebooks_collection_post_id = wp_insert_post($ebooks_collection_my_post);
        
            // If the post was successfully created, set the featured image
            if ($ebooks_collection_post_id && !is_wp_error($ebooks_collection_post_id)) {
                // Set the image URL based on the current slider index
                $ebooks_collection_image_url = esc_url(get_stylesheet_directory_uri() . '/images/slider' . $ebooks_collection_i . '.png');
                $ebooks_collection_upload_dir = wp_upload_dir();
        
                // Download the image data using wp_remote_get()
                $ebooks_collection_response = wp_remote_get($ebooks_collection_image_url);
                if (!is_wp_error($ebooks_collection_response)) {
                    $ebooks_collection_image_data = wp_remote_retrieve_body($ebooks_collection_response);
        
                    if (!empty($ebooks_collection_image_data)) {
                        // Handle the file upload process
                        $ebooks_collection_image_name = 'slider' . $ebooks_collection_i . '.png';
                        $ebooks_collection_unique_file_name = wp_unique_filename($ebooks_collection_upload_dir['path'], $ebooks_collection_image_name);
                        $ebooks_collection_file = $ebooks_collection_upload_dir['path'] . '/' . $ebooks_collection_unique_file_name;
        
                        // Save the image file to the uploads directory
                        global $wp_filesystem;
                        WP_Filesystem();
                        $wp_filesystem->put_contents($ebooks_collection_file, $ebooks_collection_image_data);
        
                        // Check file type and prepare for attachment
                        $ebooks_collection_wp_filetype = wp_check_filetype($ebooks_collection_unique_file_name, null);
                        $ebooks_collection_attachment = array(
                            'post_mime_type' => $ebooks_collection_wp_filetype['type'],
                            'post_title'     => sanitize_file_name($ebooks_collection_unique_file_name),
                            'post_content'   => '',
                            'post_status'    => 'inherit',
                        );
        
                        // Insert the image into the media library and set it as the post's featured image
                        $ebooks_collection_attach_id = wp_insert_attachment($ebooks_collection_attachment, $ebooks_collection_file, $ebooks_collection_post_id);
                        $ebooks_collection_attach_data = wp_generate_attachment_metadata($ebooks_collection_attach_id, $ebooks_collection_file);
                        wp_update_attachment_metadata($ebooks_collection_attach_id, $ebooks_collection_attach_data);
                        set_post_thumbnail($ebooks_collection_post_id, $ebooks_collection_attach_id);
                    }
                }
            }
        }

        //Service Section
        set_theme_mod( 'ebooks_collection_disabled_pgboxes', true);
        set_theme_mod( 'ebooks_collection_feature_heading', 'Book Features');

        //Category To Display Post
        $ebooks_collection_service_category_id = wp_create_category('Service');
        // Set the category in theme mods for the service section
        set_theme_mod('ebooks_collection_select_cat_services', $ebooks_collection_service_category_id); // Update with correct category ID
        
        // Titles for the three posts
        $ebooks_collection_titles = array(
            'Tips & Tricks',
            'Best Trending ebook',
        );        
        // Create three demo posts and assign them to the 'service' category
        for ($ebooks_collection_i = 1; $ebooks_collection_i <= 2; $ebooks_collection_i++) {
            $ebooks_collection_title = $ebooks_collection_titles[$ebooks_collection_i - 1];
            $ebooks_collection_content = 'Posuere tellus imperdiet faciliss.nCurabitur vivrra faucibusy.';
        
            // Prepare the post object
            $ebooks_collection_my_post = array(
                'post_title'    => wp_strip_all_tags($ebooks_collection_title),
                'post_content'  => $ebooks_collection_content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => array($ebooks_collection_service_category_id),
            );
        
            // Insert the post into the database
            $ebooks_collection_post_id = wp_insert_post($ebooks_collection_my_post);
        
            // If the post was successfully created, set the featured image
            if ($ebooks_collection_post_id && !is_wp_error($ebooks_collection_post_id)) {
                // Set the image URL based on the current service index
                $ebooks_collection_image_url = esc_url(get_stylesheet_directory_uri() . '/images/service' . $ebooks_collection_i . '.png');
                $ebooks_collection_upload_dir = wp_upload_dir();
        
                // Download the image data using wp_remote_get()
                $ebooks_collection_response = wp_remote_get($ebooks_collection_image_url);
                if (!is_wp_error($ebooks_collection_response)) {
                    $ebooks_collection_image_data = wp_remote_retrieve_body($ebooks_collection_response);
        
                    if (!empty($ebooks_collection_image_data)) {
                        // Handle the file upload process
                        $ebooks_collection_image_name = 'service' . $ebooks_collection_i . '.png';
                        $ebooks_collection_unique_file_name = wp_unique_filename($ebooks_collection_upload_dir['path'], $ebooks_collection_image_name);
                        $ebooks_collection_file = $ebooks_collection_upload_dir['path'] . '/' . $ebooks_collection_unique_file_name;
        
                        // Save the image file to the uploads directory
                        global $wp_filesystem;
                        WP_Filesystem();
                        $wp_filesystem->put_contents($ebooks_collection_file, $ebooks_collection_image_data);
        
                        // Check file type and prepare for attachment
                        $ebooks_collection_wp_filetype = wp_check_filetype($ebooks_collection_unique_file_name, null);
                        $ebooks_collection_attachment = array(
                            'post_mime_type' => $ebooks_collection_wp_filetype['type'],
                            'post_title'     => sanitize_file_name($ebooks_collection_unique_file_name),
                            'post_content'   => '',
                            'post_status'    => 'inherit',
                        );
        
                        // Insert the image into the media library and set it as the post's featured image
                        $ebooks_collection_attach_id = wp_insert_attachment($ebooks_collection_attachment, $ebooks_collection_file, $ebooks_collection_post_id);
                        $ebooks_collection_attach_data = wp_generate_attachment_metadata($ebooks_collection_attach_id, $ebooks_collection_file);
                        wp_update_attachment_metadata($ebooks_collection_attach_id, $ebooks_collection_attach_data);
                        set_post_thumbnail($ebooks_collection_post_id, $ebooks_collection_attach_id);
                    }
                }
            }
        }

        //Service Page
        // Function to fetch or create a page using WP_Query
        function get_or_create_page_by_title( $ebooks_collection_page_title, $ebooks_collection_page_content = '' ) {
            $ebooks_collection_args = array(
                'post_type'      => 'page',
                'title'          => $ebooks_collection_page_title,
                'post_status'    => 'publish',
                'posts_per_page' => 1,
                'fields'         => 'ids'
            );
            $ebooks_collection_query = new WP_Query( $ebooks_collection_args );

            if ( ! empty( $ebooks_collection_query->posts ) ) {
                return $ebooks_collection_query->posts[0];
            } else {
                // Create the page if it doesn't exist
                $ebooks_collection_page_id = wp_insert_post( array(
                    'post_type'    => 'page',
                    'post_title'   => $ebooks_collection_page_title,
                    'post_content' => $ebooks_collection_page_content,
                    'post_status'  => 'publish',
                    'post_author'  => 1
                ));
                return $ebooks_collection_page_id;
            }
        }

        // Create Page
        $ebooks_collection_page_title = 'What you will learn with this ebook?';
        $ebooks_collection_page_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';
        $ebooks_collection_page_id = get_or_create_page_by_title( $ebooks_collection_page_title, $ebooks_collection_page_content );

        if ( $ebooks_collection_page_id ) {
            set_theme_mod( 'ebooks_collection_service_page', $ebooks_collection_page_id );
        } else {
            error_log('Failed to create or fetch the "Welcome to Corporate Business Theme" page.');
        }

        // Show success message and the "View Site" button
        update_option('ebooks_collection_demo_import_completed', true);
        echo '<br>';
        echo '<div class="success">Demo Import Successful</div>';
        echo '<br>';
        echo '<hr>';
        echo '<br>';
        echo '<span>' . esc_html__( 'You can now visit your site or customize it further.', 'ebooks-collection' ) . '</span>';
        echo '<br>';
    }
     ?>
    <ul>
        <li>
        <?php 
        // Check if the form is submitted
        if ( !isset( $_POST['submit'] ) ) : ?>
            <!-- Show demo importer form only if it's not submitted -->
            <?php if (!get_option('ebooks_collection_demo_import_completed')) : ?>
                <span><?php echo esc_html( 'Click on the below content to get demo content installed.', 'ebooks-collection' ); ?></span>
                <br><br>
                <hr><br>
                <b class="note"><?php echo esc_html('Note :', 'ebooks-collection' ); ?></b><br><br>
                <small><b><?php echo esc_html('Please take a backup if your website is already live with data. This importer will overwrite existing data.', 'ebooks-collection' ); ?></b></small><br><br>
                <form id="demo-importer-form" action="" method="POST" onsubmit="return runDemoImport();">
                    <input type="submit" name="submit" value="<?php echo esc_attr('Run Importer','ebooks-collection'); ?>" class="button button-primary button-large">
                </form>
                <script type="text/javascript">
                    function runDemoImport() {
                        if (confirm('Do you really want to do this?')) {
                            document.getElementById('demo-import-loader').style.display = 'block';
                            return true;
                        }
                        return false;
                    }
                </script>
             <?php endif; ?>
         <?php 
        endif; 

        // Show "View Site" button after form submission
        if ( isset( $_POST['submit'] ) ) {
        echo '<div class="view-site-btn">';
        echo '<a href="' . esc_url(home_url()) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">View Site</a>';
        echo '<a href="' . esc_url( admin_url('customize.php') ) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">Customize Demo Content</a>';
        echo '</div>';
        }
        ?>
        </li>
    </ul>
 </div>