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

        // If the demo import is completed, display the "View Site" button
        if ($business_incubator_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.', 'business-incubator' ) . '</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>';
        }
     // POST and update the customizer and other related data of Business Incubator
    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
                $business_incubator_plugin_slug = 'classic-blog-grid';
                $business_incubator_plugin_file = 'classic-blog-grid/classic-blog-grid.php';
            
                // Check if Classic Blog Grid is installed and activated
                if ( ! is_plugin_active( $business_incubator_plugin_file ) ) {
            
                    // Check if Classic Blog Grid is installed
                    $business_incubator_installed_plugins = get_plugins();
                    if ( ! isset( $business_incubator_installed_plugins[ $business_incubator_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
                        $business_incubator_upgrader = new Plugin_Upgrader();
                        $business_incubator_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( $business_incubator_plugin_file );
                }
            }
        echo '</div>';
        // ------- Create Main Menu --------
        $business_incubator_menuname = 'Primary Menu'; 
        $business_incubator_bpmenulocation = 'primary';
        $business_incubator_menu_exists = wp_get_nav_menu_object($business_incubator_menuname);

        if (!$business_incubator_menu_exists) {
            // Create a new menu
            $business_incubator_menu_id = wp_create_nav_menu($business_incubator_menuname);

            // Define pages to be created
            $business_incubator_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>'
                ),
                'feature' => array(
                    'title' => 'Feature',
                    '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>'
                ),
                'blog' => array(
                    'title' => 'Blog',
                    'content' => ''
                ),
                '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>'
                ),
            );

            $business_incubator_page_ids = array();

            // Loop through the pages and create them if they don’t exist
            foreach ($business_incubator_pages as $business_incubator_slug => $business_incubator_data) {
                $business_incubator_existing_page = get_page_by_path($business_incubator_slug);

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

                    $business_incubator_page_id = wp_insert_post($business_incubator_page_data);

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

                // Store the page IDs
                $business_incubator_page_ids[$business_incubator_slug] = $business_incubator_page_id;
            }

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

            // Define menu items
            $business_incubator_menu_items = array(
                'home',
                'feature',
                'about-us',
                'blog',
                'pages'
            );

            // Add menu items dynamically
            foreach ($business_incubator_menu_items as $business_incubator_slug) {
                wp_update_nav_menu_item($business_incubator_menu_id, 0, array(
                    'menu-item-title' => esc_html($business_incubator_pages[$business_incubator_slug]['title']),
                    'menu-item-url' => get_permalink($business_incubator_page_ids[$business_incubator_slug]),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $business_incubator_page_ids[$business_incubator_slug],
                    'menu-item-object' => 'page',
                    'menu-item-type' => 'post_type',
                ));
            }

            // Assign menu to theme location
            $business_incubator_locations = get_theme_mod('nav_menu_locations', array());
            $business_incubator_locations[$business_incubator_bpmenulocation] = $business_incubator_menu_id;
            set_theme_mod('nav_menu_locations', $business_incubator_locations);
        }

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

        //Header Section
        set_theme_mod('business_incubator_enable_topbar', true);
        set_theme_mod( 'business_incubator_phone_number', '+123 456 789 00');
        set_theme_mod( 'business_incubator_email_address', 'support@example.com');
        set_theme_mod( 'business_incubator_instagram_link', '#');
        set_theme_mod( 'business_incubator_fb_link', '#');
        set_theme_mod( 'business_incubator_linkedin_link', '#');
        set_theme_mod( 'business_incubator_twitter_link', '#');
        set_theme_mod( 'business_incubator_header_btn_text', 'Learn More');
        set_theme_mod( 'business_incubator_header_btn_url', '#');

        //Banner Section
        set_theme_mod('business_incubator_banner', true);
        set_theme_mod('business_incubator_button_text', 'Our Service');

        // Function to fetch or create a page using WP_Query
        function get_or_create_page_by_title( $business_incubator_page_title, $business_incubator_page_content = '' ) {
            $business_incubator_args = array(
                'post_type'      => 'page',
                'title'          => $business_incubator_page_title,
                'post_status'    => 'publish',
                'posts_per_page' => 1,
                'fields'         => 'ids'
            );
            $business_incubator_query = new WP_Query( $business_incubator_args );

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

        // Create Page
        $business_incubator_page_title = 'Empowering Startups for Success';
        $business_incubator_page_content = 'Join our incubator and turn your ideas into reality with mentorship, funding, and networking.';
        $business_incubator_page_id = get_or_create_page_by_title( $business_incubator_page_title, $business_incubator_page_content );

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

        $business_incubator_image_url = get_template_directory_uri().'/images/banner.png';
        $business_incubator_image_id = media_sideload_image($business_incubator_image_url, $business_incubator_page_id, null, 'id');
        if (!is_wp_error($business_incubator_image_id)) {
            // Set the downloaded image as the post's featured image
            set_post_thumbnail($business_incubator_page_id, $business_incubator_image_id);
        }     

        //Startup Section
        set_theme_mod( 'business_incubator_disabled_startup_section', true);
        set_theme_mod( 'business_incubator_startup_sec_text', 'Fueling Startup Success');
        set_theme_mod( 'business_incubator_startup_sec_title', 'Comprehensive Support to Scale Your Business');

        $business_incubator_service_titles = array('Investor Connections', 'Startup Mentorship', 'Growth Support');
        $business_incubator_image_urls = array(
            get_template_directory_uri() . '/images/startup1.png',
            get_template_directory_uri() . '/images/startup2.png',
            get_template_directory_uri() . '/images/startup3.png'
        );
        $business_incubator_service_icons = array('fa-solid fa-landmark', 'fa-solid fa-landmark', 'fa-solid fa-landmark');

        // Loop to create posts for each service
        for ($i = 0; $i < 3; $i++) {
            $title = $business_incubator_service_titles[$i];
            $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.';
            $icon = $business_incubator_service_icons[$i];

            // Create the post object
            $post_id = wp_insert_post(array(
                'post_title'    => wp_strip_all_tags($title),
                'post_content'  => $content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
            ));

            // If the post was successfully created
            if ($post_id && !is_wp_error($post_id)) {
                // Set the theme mod for selecting this post
                set_theme_mod('business_incubator_select_post' . ($i + 1), $post_id);

                // Set the icon as a theme mod
                set_theme_mod('business_incubator_select_startup_icon' . ($i + 1), $icon);

                // Handle the featured image using media_sideload_image
                $image_url = $business_incubator_image_urls[$i];
                $image_id = media_sideload_image($image_url, $post_id, null, 'id');

                if (!is_wp_error($image_id)) {
                    set_post_thumbnail($post_id, $image_id);
                } else {
                    error_log("Failed to download image for $title: " . $image_id->get_error_message());
                }
            } else {
                error_log("Failed to create post: " . print_r($post_id, true));
            }
        }
 
        // Show success message and the "View Site" button
        update_option('business_incubator_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.', 'business-incubator' ) . '</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('business_incubator_demo_import_completed')) : ?>
                <span><?php echo esc_html( 'Click on the below content to get demo content installed.', 'business-incubator' ); ?></span>
                <br><br>
                <hr><br>
                <b class="note"><?php echo esc_html('Note :', 'business-incubator' ); ?></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.', 'business-incubator' ); ?></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','business-incubator'); ?>" 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>